Get Date based on day count in Java

后端 未结 7 1098
感情败类
感情败类 2021-01-13 21:46

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 i

相关标签:
7条回答
  • 2021-01-13 22:08
    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();
    
    0 讨论(0)
  • 2021-01-13 22:13

    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);
        }
    }
    
    0 讨论(0)
  • 2021-01-13 22:15

    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));
    
    0 讨论(0)
  • 2021-01-13 22:20

    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.

    0 讨论(0)
  • 2021-01-13 22:29

    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?

    • Java SE 8, Java SE 9, Java SE 10, and later
      • Built-in.
      • Part of the standard Java API with a bundled implementation.
      • Java 9 adds some minor features and fixes.
    • Java SE 6 and Java SE 7
      • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • Android
      • Later versions of Android bundle implementations of the java.time classes.
      • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

    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.

    0 讨论(0)
  • 2021-01-13 22:29

    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();
    
    0 讨论(0)
提交回复
热议问题