Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a number of day of the year. (Today's number of the day is 308.) I want to convert this number to a date in SQL format (YYYY/MM/DD). Can I do it in java?

Thank you in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
398 views
Welcome To Ask or Share your Answers For Others

1 Answer

tl;dr

Year.of( 2018 )
    .atDay( 308 )

2018-11-04

java.time

The modern approach uses the java.time classes built into Java 8 and later.

The LocalDate class represents a date-only value without time-of-day and without time zone.

The Year class represents, well, a year. And includes a atDay( dayOfYear ) method where you pass your ordinal day of the year.

int dayOfYear = 308 ;
Year y = Year.of( 2018 ) ;
LocalDate ld = y.atDay( dayOfYear ) ;

Dump to console.

System.out.println( "dayOfYear: " + dayOfYear + " at year: " + y + " = " + ld ) ;

See this code run live at IdeOne.com.

dayOfYear: 308 at year: 2018 = 2018-11-04

As for generating a string in a particular format, search for DateTimeFormatter class as that has been covered many many times already.

And by the way, your particular format is not at all a “SQL format”. Regardless, you should be exchanging objects with your database rather than mere strings. Look at the getObject and setObject methods in JDBC when using a driver compliant with JDBC 4.2 or later.

Database

For SQL access to a database column of SQL-standard type DATE, use JDBC 4.2 or later to pass the LocalDate object directly. Do not use mere strings to exchange date-time values.

myPreparedStatement.setObject( … , ld ) ;

Retrieval.

LocalDate ld = myResultSet.getDate( … , LocalDate.class ) ;

Table of date-time types in Java (both modern and legacy) and in standard SQL.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...