简体   繁体   中英

Converting a year and day (e.g. 2013216 = the 216th day of 2013) into a full date in Java

Context: I have two tables in a Database, onee which stores a date as a day of the year appended to the year itself, and one which stores a date as a full date. I need to compare the two so I only select rows from table B where the full date is the same day as the day date in table A.

I have a date as a year and a day (such as 2014234 which is the 234th day of this year) and I need to convert it into a full date format like: 11-OCT-13 15.30.54.000000000 +02:00 so I can compare the two for the purpose of selecting fields from a table the rows where the day the full date(eg 11-OCT) is the same as the day of day date (eg 2014235).

Anyone know how to do this?

Thanks.

EDIT: Thanks for your help everyone! I've managed to get the date converted, I've now got two dates in the same format, and I need to only select the rows where a column has the same DAY as the date in the other table, how can I do this? Using = checks that the two dates are equal to the millisecond, I only want to check that they are the same to the day. Do you know how I would go about this in an SQL query? Or will '11-OCT-13 = 11-OCT-13 15.30.54.000000000 +02:00' return true, for example?

You can use SimpleDateFormat to parse that:

DateFormat dt = new SimpleDateFormat("yyyyDDD");
Date dt = dt.parse(theString, 0);

y is the "year" field, D is the "day in year" field.

If you need to then convert it back to a string in another format, you can use another instance with the relevant format and its format method.

使用以下内容:

Date date = new SimpleDateFormat("yyyyDD").parse(String.valueOf(234));

ISO 8601 – Ordinal Date

Your String format is called an ordinal date in the ISO 8601 format. The standard define an expanded version with a hyphen between the year and the day-of-year as well as the basic format you have in hand where the hyphen is omitted.

I suggest using the hyphen as it is more recognizable and readable for humans.

Avoid juDate and .Calendar

The java.util.Date and .Calendar classes bundled with Java are notoriously troublesome. Avoid them. Instead use either Joda-Time or the new java.time package bundled with Java 8.

Both Joda-Time and java.time offer a LocalDate class to represent a date-only without any time-of-day or time zone.

Joda-Time

Joda-Time has great support for ISO 8601 formats.

Here is some example code using Joda-Time 2.4.

String input = "2013216";
DateTimeFormatter formatter = ISODateTimeFormatter.basicOrdinalDate();
LocalDate localDate = formatter.parseLocalDate( input" );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM