4

Simple Question, but Google surprisingly had little on this. I have the number of days from Jan 1st of the year. How can I convert that to a date in Java?

Maximin
  • 1,655
  • 1
  • 14
  • 32
J86
  • 14,345
  • 47
  • 130
  • 228

7 Answers7

7

You can simply use SimpleDateFormat to convert String to Date. The pattern D can be used to represent the day number of year.

Provided that you've an

int numberOfDays = 42; // Arbitrary number.

then this one counts the number of days since 1 Jan 1970 (the Epoch)

Date date = new SimpleDateFormat("D").parse(String.valueOf(numberOfDays));

alternatively, this one counts the number of days since 1 Jan of current year.

Date date = new SimpleDateFormat("D yyyy").parse(numberOfDays + " " + Calendar.getInstance().get(Calendar.YEAR));
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • I like this one. Is there a way I can add the number of minutes since mid-night in there too? – J86 Apr 26 '13 at 03:36
3

Use Calendar for date arithmetic

    Calendar c = Calendar.getInstance();
    c.set(Calendar.YEAR, 2013);
    c.set(Calendar.MONTH, Calendar.JANUARY);
    c.set(Calendar.DATE, 1);
    c.set(Calendar.HOUR, 0);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);
    c.add(Calendar.DATE, numberOfDays);
    Date date = c.getTime();

Note that the result may be different for different locales because of DST (summer time). The above example uses default locale.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Jul 13 '18 at 23:26
2

I find JodaTime very elegant to use when it comes to date handling. With it, you could do it like this:

DateTime date = new DateTime().withDayOfYear(dayOfYear);
NilsH
  • 13,705
  • 4
  • 41
  • 59
2

tl;dr

Year.of( 2017 )
    .atDay( 159 )

2017-06-08

…or for current year…

Year.now( ZoneId.of( "America/Montreal" ) )
    .atDay( 159 )

2018-06-08

Going the other direction, from date to day-of-year.

LocalDate.now( ZoneId.of( "America/Montreal" )
         .getDayOfYear()

159

Using java.time

The modern way to handle date-time is with the java.time classes. The troublesome old date-time package. The troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleTextFormat are now legacy, supplanted by the java.time classes.

The Year class represents a year, obviously. To get the current year we need the current date.

A time zone is crucial in determining a date, and therefore year. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec. In the same way, a few minutes after midnight in Paris on New Year's Day is a new year while still “last year” in Québec.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" );
Year year = Year.now( z );

If you have a specific year in mind, pass the year number.

Year year = Year.of( 2017 );

The Year class includes a method atDay for generating a LocalDate when passed a day-of-year number running from 1 to 365 or 366 in a Leap Year. The LocalDate class represents a date-only value without time-of-day and without time zone.

LocalDate localDate = year.atDay( 159 );

Going the other direction, you can interrogate a LocalDate for its day-of-year by calling LocalDate::getDayOfYear.

int dayOfYear = localDate.getDayOfYear() ;

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.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

If you are Android developer and using JodaTime this is how you get equivalent of this in java 8.

LocalDate.ofYearDay("2020", 255).getDayOfWeek().getValue()

Use this because ofYearDay is only supported above Android >= 26;

MutableDateTime mutableDateTime1 = new MutableDateTime();
mutableDateTime1.setYear("2020");
mutableDateTime1.setDayOfYear(255);
LocalDate.fromDateFields(mutableDateTime1.toDate()).getDayOfWeek();
Sabri Meviş
  • 2,231
  • 1
  • 32
  • 38
  • 2
    FYI, the [*Joda-Time*](http://www.joda.org/joda-time/) project is now in maintenance mode, with the team advising migration to the [*java.time*](http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes. Much of the *java.time* functionality is back-ported to Java 6 & Java 7 in the [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) project. Further adapted for earlier Android in the [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP) project. See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). – Basil Bourque Jul 13 '18 at 23:24
0

Using GregorianCalendar and simpleDateFormat:

int days = 20;
GregorianCalendar dayCountofYear = new GregorianCalendar(2020,Calendar.JANUARY, 1);
dayCountofYear.add(Calendar.DAY_OF_YEAR, days);
System.out.println("GregorianCalendar: "+ dateFormat.format(dayCountofYear.getTime()));

Above logic can be simplified in a function call as below:

Date nextDate = addDaysToDate("01/01/2020", 20);
System.out.println("After Adding Number of Days:"+nextDate); // O/P:21/01/2020

Full Example:

public class DateHelper {

    public static void main(String[] args) throws ParseException {
        int days = 20;
        String initialDay = "01/01/2020";
        Date nextDate = addDaysToDate(initialDay, days);
        System.out.println("After Adding Number of Days:"+nextDate);

        /*Date firstDate = DateHelper.parseDate(initialDay, formatStr);
        int daysBetween = getDaysBetween(firstDate, nextDate);
        System.out.println(days + " - Days Between - "+daysBetween);*/
    }

    static String formatStr = "dd/MM/yyyy";
    static DateFormat dateFormat = new SimpleDateFormat(formatStr);
    static DateFormat reverseDateFormat = new SimpleDateFormat("yyyy/MM/dd");

    public static Date addDaysToDate(String specificDate, int daysCount) throws ParseException {
        Date date = dateFormat.parse(specificDate);
        GregorianCalendar gregCal = (GregorianCalendar) GregorianCalendar.getInstance(); // Current Date
        gregCal.setTime(date); // Change the Date to Provided One
        gregCal.add(Calendar.DAY_OF_YEAR, daysCount);
        Date time = gregCal.getTime();

        ZonedDateTime zdt = gregCal.toZonedDateTime();
        System.out.println("GregorianCalendar DayofWeek: "+ zdt.getDayOfWeek());
        return time;
    }
    public static String addDaysToDateStr(String specificDate, int daysCount) throws ParseException {
        String format = dateFormat.format( addDaysToDate(specificDate, daysCount) );
        System.out.println("GregorianCalendar [To a Date added Number of days leads to New Date]: "+ format);
        return format;
    }
    public static Date parseDate(String aSource, String formatStr) throws ParseException {
        DateFormat dateFormat = new SimpleDateFormat(formatStr);
        dateFormat.setLenient(false);
        return dateFormat.parse(aSource);
    }
    public static String formatDate(Date aDate, String formatStr, Calendar calendar) {
        DateFormat dateFormat = new SimpleDateFormat(formatStr);
        dateFormat.setLenient(false);
        dateFormat.setCalendar(calendar);
        return dateFormat.format(aDate);
    }
    public static String formatDate(Date aDate, String formatStr) {
        DateFormat dateFormat = new SimpleDateFormat( formatStr );
        //dateFormat.setCalendar(Calendar.getInstance(TimeZone.getTimeZone("UTF")));
        return dateFormat.format(aDate);
    }
}
Yash
  • 9,250
  • 2
  • 69
  • 74
  • 1
    FYI, the terribly flawed date-time classes such as [`java.util.Date`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/tutorial/datetime/TOC.html) classes built into Java 8 and later. Suggesting their use in 2020 is poor advice. – Basil Bourque Jan 02 '20 at 01:13
  • Why on Earth? `SimpleDateFormat` is notoriously troublesome and `GregorianCalendar` poorly designed too. Both are long outdated. Who needs an answer using those classes in 2020? Nobody in the world IMHO. – Ole V.V. Jan 02 '20 at 06:34
-1
Calendar c = Calendar.getInstance();
         c.set(Calendar.YEAR, 2016);
         c.set(Calendar.MONTH, 8);
         c.set(Calendar.DAY_OF_YEAR, 244);
         c.set(Calendar.HOUR, 0);
         c.set(Calendar.MINUTE, 0);
         c.set(Calendar.SECOND, 0);
         c.set(Calendar.MILLISECOND, 0);
        Date date = c.getTime();
  • 5
    While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – J. Chomel Feb 17 '17 at 09:59