Rectangle 27 43

Example Code in Joda-Time 2.3

The java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat classes were rushed too quickly when Java first launched and evolved. The classes were not well designed or implemented. Improvements were attempted, thus the deprecations youve found. Unfortunately the attempts at improvement largely failed. You should avoid these classes altogether. They are supplanted in Java 8 by new classes.

A java.util.Date has both a date and a time portion. You ignored the time portion in your code. So the Date class will take the beginning of the day as defined by your JVMs default time zone and apply that time to the Date object. So the results of your code will vary depending on which machine it runs or which time zone is set. Probably not what you want.

If you want just the date, without the time portion, such as for a birth date, you may not want to use a Date object. You may want to store just a string of the date, in ISO 8601 format of YYYY-MM-DD. Or use a LocalDate object from Joda-Time (see below).

Avoid the notoriously troublesome java.util.Date & java.util.Calendar classes

DateTimeZone timeZoneNorway = DateTimeZone.forID( "Europe/Oslo" );
DateTime birthDateTime_InNorway = new DateTime( 1985, 1, 1, 3, 2, 1, timeZoneNorway );

DateTimeZone timeZoneNewYork = DateTimeZone.forID( "America/New_York" );
DateTime birthDateTime_InNewYork = birthDateTime_InNorway.toDateTime( timeZoneNewYork ); 

DateTime birthDateTime_UtcGmt = birthDateTime_InNorway.toDateTime( DateTimeZone.UTC );

LocalDate birthDate = new LocalDate( 1985, 1, 1 );
System.out.println( "birthDateTime_InNorway: " + birthDateTime_InNorway );
System.out.println( "birthDateTime_InNewYork: " + birthDateTime_InNewYork );
System.out.println( "birthDateTime_UtcGmt: " + birthDateTime_UtcGmt );
System.out.println( "birthDate: " + birthDate );
birthDateTime_InNorway: 1985-01-01T03:02:01.000+01:00
birthDateTime_InNewYork: 1984-12-31T21:02:01.000-05:00
birthDateTime_UtcGmt: 1985-01-01T02:02:01.000Z
birthDate: 1985-01-01

In this case the code for java.time is nearly identical to that of Joda-Time.

We get a time zone (ZoneId), and construct a date-time object assigned to that time zone (ZonedDateTime). Then using the Immutable Objects pattern, we create new date-times based on the old objects same instant (count of nanoseconds since epoch) but assigned other time zone. Lastly we get a LocalDate which has no time-of-day nor time zone though notice the time zone applies when determining that date (a new day dawns earlier in Oslo than in New York for example).

ZoneId zoneId_Norway = ZoneId.of( "Europe/Oslo" );
ZonedDateTime zdt_Norway = ZonedDateTime.of( 1985 , 1 , 1 , 3 , 2 , 1 , 0 , zoneId_Norway );

ZoneId zoneId_NewYork = ZonedId.of( "America/New_York" );
ZonedDateTime zdt_NewYork = zdt_Norway.withZoneSameInstant( zoneId_NewYork );

ZonedDateTime zdt_Utc = zdt_Norway.withZoneSameInstant( ZoneOffset.UTC );  // Or, next line is similar.
Instant instant = zdt_Norway.toInstant();  // Instant is always in UTC.

LocalDate localDate_Norway = zdt_Norway.toLocalDate();

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.

  • Part of the standard Java API with a bundled implementation.
  • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

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.

Props for actually mentioning the root cause and providing coverage of all available alternatives.

Java: Why is the Date constructor deprecated, and what do I use instea...

java date deprecated
Rectangle 27 1

Example Code in Joda-Time 2.3

Building on the correct answers by Pawe Dyda & Knubo

You should never store (serialize) a date-time as a string in the format you mentioned: "30/03/2008 03:00:00". Problems:

  • Should have been translated to UTC time.

If you must serialize a date-time value to text, use a reliable format. The obvious choice is the ISO 8601 standard format. Even better is converting the local time to UTC (Zulu) time zone and then out to ISO 8601 format. Like this: 2013-11-01T04:48:53.044Z

The midnight methods in Joda-Time are deprecated in favor of the Joda-Time method withTimeAtStartOfDay() (see doc). Some days do not have a midnight.

Some comments about this source code:

//  2013 Basil Bourque. This source code may be used freely forevery by anyone taking full responsibility for doing so.

    // Joda-Time - The popular alternative to Sun/Oracle's notoriously bad date, time, and calendar classes bundled with Java 7 and earlier.
    // http://www.joda.org/joda-time/

    // Joda-Time will become outmoded by the JSR 310 Date and Time API introduced in Java 8.
    // JSR 310 was inspired by Joda-Time but is not directly based on it.
    // http://jcp.org/en/jsr/detail?id=310

    // By default, Joda-Time produces strings in the standard ISO 8601 format.
    // https://en.wikipedia.org/wiki/ISO_8601

Example showing 23 hours in the day of DST (Daylight Saving Time) in Rome Italy, while the day after has 24 hours. Note that the time zone (for Rome) is specified.

// Time Zone list: http://joda-time.sourceforge.net/timezones.html
    org.joda.time.DateTimeZone romeTimeZone = org.joda.time.DateTimeZone.forID("Europe/Rome");
    org.joda.time.DateTime dayOfDstChange = new org.joda.time.DateTime( 2008, 3, 30, 0, 0, romeTimeZone ) ; // Day when DST
    org.joda.time.DateTime dayAfter = dayOfDstChange.plusDays(1);

    // How many hours in this day? Should be 23 rather than 24 on day of Daylight Saving Time "springing ahead" to lose one hour.
    org.joda.time.Hours hoursObjectForDay = org.joda.time.Hours.hoursBetween(dayOfDstChange.withTimeAtStartOfDay(), dayAfter.withTimeAtStartOfDay());
    System.out.println( "Expect 23 hours, got: " + hoursObjectForDay.getHours() ); // Extract an int from object.

    // What time is 3 hours after midnight on day of DST change?
    org.joda.time.DateTime threeHoursAfterMidnightOnDayOfDst = dayOfDstChange.withTimeAtStartOfDay().plusHours(3);
    System.out.println( "Expect 4 AM (04:00) for threeHoursAfterMidnightOnDayOfDst: " + threeHoursAfterMidnightOnDayOfDst );

    // What time is 3 hours after midnight on day _after_ DST change?
    org.joda.time.DateTime threeHoursAfterMidnightOnDayAfterDst = dayAfter.withTimeAtStartOfDay().plusHours(3);
    System.out.println( "Expect 3 AM (03:00) for threeHoursAfterMidnightOnDayAfterDst: " + threeHoursAfterMidnightOnDayAfterDst );

Example of storing a date-time by first translating to UTC. Then upon restoring the date-time object, adjust to the desired time zone.

// Serialize DateTime object to text.
    org.joda.time.DateTimeZone romeTimeZone = org.joda.time.DateTimeZone.forID("Europe/Rome");
    org.joda.time.DateTime dayOfDstChangeAtThreeHoursAfterMidnight = new org.joda.time.DateTime( 2008, 3, 30, 0, 0, romeTimeZone ).withTimeAtStartOfDay().plusHours(3);
    System.out.println("dayOfDstChangeAtThreeHoursAfterMidnight: " + dayOfDstChangeAtThreeHoursAfterMidnight);
    // Usually best to first change to UTC (Zulu) time when serializing.
    String dateTimeSerialized = dayOfDstChangeAtThreeHoursAfterMidnight.toDateTime( org.joda.time.DateTimeZone.UTC ).toString();
    System.out.println( "dateTimeBeingSerialized: " + dateTimeSerialized );
    // Restore
    org.joda.time.DateTime restoredDateTime = org.joda.time.DateTime.parse( dateTimeSerialized );
    System.out.println( "restoredDateTime: " + restoredDateTime );
    // Adjust to Rome Italy time zone.
    org.joda.time.DateTime restoredDateTimeAdjustedToRomeItaly = restoredDateTime.toDateTime(romeTimeZone);
    System.out.println( "restoredDateTimeAdjustedToRomeItaly: " + restoredDateTimeAdjustedToRomeItaly );
dayOfDstChangeAtThreeHoursAfterMidnight: 2008-03-30T04:00:00.000+02:00
dateTimeBeingSerialized: 2008-03-30T02:00:00.000Z
restoredDateTime: 2008-03-30T02:00:00.000Z
restoredDateTimeAdjustedToRomeItaly: 2008-03-30T04:00:00.000+02:00

java - Joda-Time, Daylight Saving Time change and date time parsing - ...

java parsing jodatime dst
Rectangle 27 5

WEEKOFYEAR() in MySQL

While I do not have much experience with working in weeks, it seems to me the wisest approach would be to follow the ISO 8601 standard. That standard clearly defines a week and week numbers.

  • Week starts on a Monday.
  • The first week contains the year's first Thursday.
01
53
00

Mode 3 of the WEEK( date, mode ) function appears to comply with ISO 8601, where first day of week is Monday, weeks are numbered 1-53, has 4 or more days this year (not official definition, but another way to say 'contains first Thursday').

Furthermore, MySQL offers the WEEKOFYEAR( date ) function specifically as shorthand for calling WEEK with mode 3. So I suggest you stick with calling WEEKOFYEAR.

Time zone is crucial. The date is determined by time zone. While Montal is enjoying the last moments before midnight on the Wednesday night of 2012-12-12, in Paris Thursday has already arrived with the date being the 13th. Same moment in the history of the Universe, but different date and time.

I assume, but do not know, that MySQL stores date-time values in UTC. So I assume too that calling their week-related functions are effectively working in UTC by not applying any time zone adjustment.

I suspect this may be the root of your problem. The java.util.Calendar class assigns the JVMs default time zone if you neglect to specify one. By the way, that's an important lesson: Always specify a time zone rather than rely on implicit default. So MySQL is calculating week-of-year by UTC and Calendar is calculating by some other time zone (Paris, Kolkata, whatever) then obviously results will be different.

My guess is that the solution is to either:

  • Consistently do your Java work using UTC
  • Apply a time zone adjustment to your date-time values in MySQL (if that is possible, I don't know).

Which of those solutions is best depends on your business policy. Some businesses may want to work by the time zone of their home office, or key supplier/customer, etc. Other businesses, especially those with concerns in various time zones choose to define everything in UTC.

I suspect the wisest choice in the long-term for most folks in this era of a shrinking world would be to always work in UTC. But I am not the person running your company.

As for the Java side of things, avoid using the java.util.Date & .Calendar classes. They are notoriously troublesome. Even Sun/Oracle has given up on them, supplanting them with the new java.time package in Java 8. That package was inspired by Joda-Time. Joda-Time continues as a viable project, with java.time and Joda-Time each having their strengths and weaknesses. Both support ISO 8601 very well, and use the standard for many of their default behaviors. Both have support for week-of-year. The Joda-Time team has asked us to migrate to java.time.

Much of the java.time functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

The OffsetDateTime class represents a point on the timeline, with a resolution of nanoseconds, adjusted to an offset-from-UTC (not a full time zone).

OffsetDateTime twelves = OffsetDateTime.of( 2012, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC );

The OffsetDateTime::get method lets you access any part of the value. Each part is defined as a TemporalField. The IsoFields class provides implementations of TemporalField specific to the ISO-8601 calendar system. This includes the two we need:

int week = twelves.get ( IsoFields.WEEK_OF_WEEK_BASED_YEAR );
int weekYear = twelves.get ( IsoFields.WEEK_BASED_YEAR );

A time zone is an offset-from-UTC plus a set of rules for handling anomalies such as Daylight Saving Time (DST). In some time zones the day does not begin at 00:00:00.0. So we go through the LocalDate class (a date-only value) to let java.time determine the first moment of the day.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate twelves = LocalDate.of( 2012 , 12 , 12 );
ZonedDateTime twelvesMontreal = twelves.atStartOfDay( zoneId );
int week = twelvesMontreal.get ( IsoFields.WEEK_OF_WEEK_BASED_YEAR );
int weekYear = twelvesMontreal.get ( IsoFields.WEEK_BASED_YEAR );

If you are sure time-of-day and time zone is irrelevant (think twice about that!), then you can use LocalDate alone as it too has a get method.

LocalDate twelves = LocalDate.of( 2012 , 12 , 12 );
int week = twelves.get ( IsoFields.WEEK_OF_WEEK_BASED_YEAR );
int weekYear = twelves.get ( IsoFields.WEEK_BASED_YEAR );

The method getWeekOfWeekYear gets the week number. The ISODateTimeFormat class has factory methods for producing formatters for the various week-related formats defined by ISO 8601.

DateTime twelves = new DateTime( 2012, 12, 12, 0, 0, 0, DateTimeZone.UTC );
int weekOfTwelves = twelves.getWeekOfWeekyear();

Create string representations. Note that you could append a call to withZone if you want the formatter to apply a time zone adjustment to its string generation. Otherwise, the DateTime's assigned time zone is utilized.

String outputWeek = ISODateTimeFormat.weekyearWeek().print(  twelves );
String outputWeekDate = ISODateTimeFormat.weekDate().print(  twelves );
System.out.println( "twelves: " + twelves );
System.out.println( "weekOfTwelves: " + weekOfTwelves );
System.out.println( "outputWeek: " + outputWeek );
System.out.println( "outputWeekDate: " + outputWeekDate );
twelves: 2012-12-12T00:00:00.000Z
weekOfTwelves: 50
outputWeek: 2012-W50
outputWeekDate: 2012-W50-3

As for porting to database other than MySQL, I assume that sticking with the increasingly-common ISO 8601 standard will help with portability.

Postgres for example offers the functions isoyear, week, and isodow (day-of-week), documented as complying with ISO 8601.

Week of year calculation differences among Java and multi SQL RDBMS - ...

java sql date datetime week-number
Rectangle 27 5

Yes, you should use either Joda-Time or the new java.time package in Java 8 (inspired by Joda-Time).

An offset is the number hours and minutes from UTC (GMT) that is represented by a certain date-time value. West coast is -08:00 (ignoring Daylight Saving Time nonsense), meaning 8 hours behind UTC.

Beware that java.time in its initial release has a small bug where it fails to handle an offset of just hours (such as +08) without minutes (such as +08:00).

A time zone is an offset plus rules about Daylight Saving Time (DST), history of DST changes, and information about other anomalies.

Use proper time zone names (mostly continent slash city). Avoid the 3 or 4 letter codes, such as EST, which are neither standardized nor unique.

A java.util.Date has no time zone, while a Joda-Time DateTime does.

To get a web browser's time zone, see this question. But often, this does not work well. As you've probably seen, many web sites ask the user to choose a time zone.

Your exact use-case is confusing. Generally the best approach is to use date-time values for UTC, then adjust to user's local time as needed. Usually best for your software to work and store date-times as UTC. Then present a local date-time adjusted to suit the user. In other words, think globally (UTC), present locally (local time zone adjusted).

Usually sysadmins keep their server computers set to UTC (no time zone offset). If your OS (like Mac OS X) does not offer UTC, then use Reykjavik as Iceland uses UTC year-round without any Daylight Saving Time. Likewise, database engines almost always convert date-time values to UTC for storage.

Joda-Time does offer a LocalDate class for when you truly do not care about time zone or time. But often it is better to use a date-time (a DateTime instance), and format for a date-only string as needed.

Example code in Joda-Time 2.3.

DateTimeZone timeZoneChina = DateTimeZone.forID( "Asia/Shanghai" );
DateTime dateTimeChina = new DateTime( 2013, 8, 29, 17, 45, 00, timeZoneChina );
DateTime dateTimeUtc = dateTimeChina.withZone( DateTimeZone.UTC );
DateTime dateTimeParis = dateTimeChina.withZone( DateTimeZone.forID( "Europe/Paris" ) );

DateTimeZone timeZoneUsWestCoast = DateTimeZone.forID( "America/Los_Angeles" );
DateTime dateTimeUnitedStatesWestCoast = dateTimeChina.withZone( timeZoneUsWestCoast );

DateTimeFormatter formatter = ISODateTimeFormat.date();
String outputDateOnlyForUnitedStatesWestCoast = formatter.withZone( timeZoneUsWestCoast ).print( dateTimeUtc );
System.out.println( "dateTimeChina: " + dateTimeChina );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "dateTimeParis: " + dateTimeParis );
System.out.println( "dateTimeUnitedStatesWestCoast: " + dateTimeUnitedStatesWestCoast );
System.out.println( "outputDateOnlyForUnitedStatesWestCoast: " + outputDateOnlyForUnitedStatesWestCoast );
dateTimeChina: 2013-08-29T17:45:00.000+08:00
dateTimeUtc: 2013-08-29T09:45:00.000Z
dateTimeParis: 2013-08-29T11:45:00.000+02:00
dateTimeUnitedStatesWestCoast: 2013-08-29T02:45:00.000-07:00
outputDateOnlyForUnitedStatesWestCoast: 2013-08-29

datetime - Daylight saving time in java - Stack Overflow

java datetime timezone
Rectangle 27 31

The java.util.Date class has no time zone assigned, yet it's toString implementation confusingly applies the JVM's current default time zone.

This is one of many reasons to avoid the notoriously troublesome java.util.Date, .Calendar, and SimpleDateFormat classes bundled with Java. Avoid them. Instead use either:

  • The java.time package built into Java 8 and inspired by Joda-Time.

Java 8 and later has the java.time package built-in. This package was inspired by Joda-Time. While they share some similarities and class names, they are different; each has features the other lacks. One notable difference is that java.time avoids constructors, instead uses static instantiation methods. Both frameworks are led by the same man, Stephen Colbourne.

Much of the java.time functionality has been back-ported to Java 6 & 7 in the ThreeTen-Backport project. Further adapted to Android in the ThreeTenABP project.

In the case of this Question, they work in the same fashion. Specify a time zone, and call a now method to get current moment, then create a new instance based on the old immutable instance to adjust for time zone.

Note the two different time zone classes. One is a named time zone including all the rules for Daylight Saving Time and other such anomalies plus an offset from UTC while the other is only the offset.

ZoneId zoneMontral = ZoneId.of("America/Montreal"); 
ZonedDateTime nowMontral = ZonedDateTime.now ( zoneMontral );

ZoneId zoneTokyo = ZoneId.of("Asia/Tokyo"); 
ZonedDateTime nowTokyo = nowMontral.withZoneSameInstant( zoneTokyo );

ZonedDateTime nowUtc = nowMontral.withZoneSameInstant( ZoneOffset.UTC );

Some example code in Joda-Time 2.3 follows. Search StackOveflow for many more examples and much discussion.

DateTimeZone timeZoneLondon = DateTimeZone.forID( "Europe/London" );
DateTimeZone timeZoneKolkata = DateTimeZone.forID( "Asia/Kolkata" );
DateTimeZone timeZoneNewYork = DateTimeZone.forID( "America/New_York" );

DateTime nowLondon = DateTime.now( timeZoneLondon ); // Assign a time zone rather than rely on implicit default time zone.
DateTime nowKolkata = nowLondon.withZone( timeZoneKolkata );
DateTime nowNewYork = nowLondon.withZone( timeZoneNewYork );
DateTime nowUtc = nowLondon.withZone( DateTimeZone.UTC );  // Built-in constant for UTC.

We have four representations of the same moment in the timeline of the Universe.

Actually the java.util.Date class does have a time zone buried within its source code. But the class ignores that time zone for most practical purposes. So, as shorthand, its often said that j.u.Date has no time zone assigned. Confusing? Yes. Avoid the mess that is j.u.Date and go with Joda-Time and/or java.time.

Thanks, It was very useful your answer.

java - Timezone conversion - Stack Overflow

java datetime timezone
Rectangle 27 31

The java.util.Date class has no time zone assigned, yet it's toString implementation confusingly applies the JVM's current default time zone.

This is one of many reasons to avoid the notoriously troublesome java.util.Date, .Calendar, and SimpleDateFormat classes bundled with Java. Avoid them. Instead use either:

  • The java.time package built into Java 8 and inspired by Joda-Time.

Java 8 and later has the java.time package built-in. This package was inspired by Joda-Time. While they share some similarities and class names, they are different; each has features the other lacks. One notable difference is that java.time avoids constructors, instead uses static instantiation methods. Both frameworks are led by the same man, Stephen Colbourne.

Much of the java.time functionality has been back-ported to Java 6 & 7 in the ThreeTen-Backport project. Further adapted to Android in the ThreeTenABP project.

In the case of this Question, they work in the same fashion. Specify a time zone, and call a now method to get current moment, then create a new instance based on the old immutable instance to adjust for time zone.

Note the two different time zone classes. One is a named time zone including all the rules for Daylight Saving Time and other such anomalies plus an offset from UTC while the other is only the offset.

ZoneId zoneMontral = ZoneId.of("America/Montreal"); 
ZonedDateTime nowMontral = ZonedDateTime.now ( zoneMontral );

ZoneId zoneTokyo = ZoneId.of("Asia/Tokyo"); 
ZonedDateTime nowTokyo = nowMontral.withZoneSameInstant( zoneTokyo );

ZonedDateTime nowUtc = nowMontral.withZoneSameInstant( ZoneOffset.UTC );

Some example code in Joda-Time 2.3 follows. Search StackOveflow for many more examples and much discussion.

DateTimeZone timeZoneLondon = DateTimeZone.forID( "Europe/London" );
DateTimeZone timeZoneKolkata = DateTimeZone.forID( "Asia/Kolkata" );
DateTimeZone timeZoneNewYork = DateTimeZone.forID( "America/New_York" );

DateTime nowLondon = DateTime.now( timeZoneLondon ); // Assign a time zone rather than rely on implicit default time zone.
DateTime nowKolkata = nowLondon.withZone( timeZoneKolkata );
DateTime nowNewYork = nowLondon.withZone( timeZoneNewYork );
DateTime nowUtc = nowLondon.withZone( DateTimeZone.UTC );  // Built-in constant for UTC.

We have four representations of the same moment in the timeline of the Universe.

Actually the java.util.Date class does have a time zone buried within its source code. But the class ignores that time zone for most practical purposes. So, as shorthand, its often said that j.u.Date has no time zone assigned. Confusing? Yes. Avoid the mess that is j.u.Date and go with Joda-Time and/or java.time.

Thanks, It was very useful your answer.

java - Timezone conversion - Stack Overflow

java datetime timezone
Rectangle 27 8

The accepted answer is correct. The java.util.Date class has no time zone assigned, yet it's toString implementation confusingly applies the JVM's current default time zone.

This is one of many reasons to avoid the notoriously troublesome java.util.Date, .Calendar, and SimpleDateFormat classes bundled with Java. Avoid them. Instead use either:

  • The new java.time package bundled with Java 8 and inspired by Joda-Time.

Some example code in Joda-Time 2.3 follows. Search StackOveflow for many more examples and much discussion.

DateTimeZone timeZoneLondon = DateTimeZone.forID( "Europe/London" );
DateTimeZone timeZoneAthens = DateTimeZone.forID( "Europe/Athens" );

DateTime nowLondon = DateTime.now( timeZoneLondon );
DateTime nowAthens = nowLondon.withZone( timeZoneAthens );
DateTime nowUtc = nowLondon.withZone( DateTimeZone.UTC );

Java 8 and later has a new java.time package built-in. This package was inspired by Joda-Time. While they share some similarities and class names, they are different; each has features the other lacks. One notable difference is that java.time avoids constructors, instead uses static instantiation methods.

In the case of this Question, they work in the same fashion. Specify a time zone, and call a now method to get current moment, then create a new instance based on the old immutable instance to adjust for time zone.

Note the two different time zone classes. One is a named time zone including all the rules for Daylight Saving Time and other such anomalies plus an offset from UTC while the other is only the offset.

ZoneId zoneMontral = ZoneId.of("America/Montreal"); 
ZonedDateTime nowMontral = ZonedDateTime.now ( zoneMontral );

ZoneId zoneTokyo = ZoneId.of("Asia/Tokyo"); 
ZonedDateTime nowTokyo = nowMontral.withZoneSameInstant( zoneTokyo );

ZonedDateTime nowUtc = nowMontral.withZoneSameInstant( ZoneOffset.UTC );

Actually the java.util.Date class does have a time zone buried within its source code. But the class ignores that time zone for most practical purposes. So, as shorthand, its often said that j.u.Date has no time zone assigned. Confusing? Yes. Avoid the mess that is j.u.Date and go with Joda-Time and/or java.time.

java - Convert date to different timezone - Stack Overflow

java date datetime calendar timezone
Rectangle 27 18

LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) ) ;
Boolean isBetween = 
    ( ! today.isBefore( localDate1 ) )  // not-before is short for is-equal-to or later-than.
    &&
    today.isBefore( localDate3 ) ;

Half-open approach, where beginning is inclusive while ending is exclusive.

By the way, that is a bad choice of format for a text representation of a date or date-time value. Whenever possible, stick with the standard ISO 8601 formats. ISO 8601 formats are unambiguous, understandable across human cultures, and are easy to parse by machine.

For a date-only value, the standard format is YYYY-MM-DD. Note how this format has the benefit of being chronological when sorted alphabetically.

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

A time zone is crucial in determining a date. 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 Montral Qubec.

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );

As your input strings are non-standard format, we must define a formatting pattern to match.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" );

Use that to parse the input strings.

LocalDate start = LocalDate.parse( "22-02-2010" , f );
LocalDate stop = LocalDate.parse( "25-12-2010" , f );

In date-time work, usually best to define a span of time by the Half-Open approach where the beginning is inclusive while the ending is exclusive. So we want to know if today is the same or later than the start and also before the stop. A briefer way of saying is the same or later than the start is not before the start.

Boolean intervalContainsToday = ( ! today.isBefore( start ) ) && today.isBefore( stop ) ;

See the Answer by gstackoverflow showing the list of comparison methods you can call.

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.

  • Part of the standard Java API with a bundled implementation.
  • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

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.

UPDATE: This Joda-Time section below is left intact as history. The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

Other answers are correct with regard to the bundled java.util.Date and java.util.Calendar classes. But those classes are notoriously troublesome. So here's some example code using the Joda-Time 2.3 library.

If you truly want a date without any time portion and no time zone, then use the LocalDate class in Joda-Time. That class provides methods of comparison including compareTo (used with Java Comparators), isBefore, isAfter, and isEqual.

String string1 = "22-02-2010";
String string2 = "07-04-2010";
String string3 = "25-12-2010";

Define a formatter describing the input strings

DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd-MM-yyyy" );

Use formatter to parse the strings into LocalDate objects

LocalDate localDate1 = formatter.parseLocalDate( string1 );
LocalDate localDate2 = formatter.parseLocalDate( string2 );
LocalDate localDate3 = formatter.parseLocalDate( string3 );

boolean is1After2 = localDate1.isAfter( localDate2 );
boolean is2Before3 = localDate2.isBefore( localDate3 );
System.out.println( "Dates: " + localDate1 + " " + localDate2 + " " + localDate3 );
System.out.println( "is1After2 " + is1After2 );
System.out.println( "is2Before3 " + is2Before3 );
Dates: 2010-02-22 2010-04-07 2010-12-25
is1After2 false
is2Before3 true

So see if the second is between the other two (exclusively, meaning not equal to either endpoint)

boolean is2Between1And3 = ( ( localDate2.isAfter( localDate1 ) ) && ( localDate2.isBefore( localDate3 ) ) );

If you are working with spans of time, I suggest exploring in Joda-Time the classes: Duration, Interval, and Period. Methods such as overlap and contains make comparisons easy.

  • durationFormat: PnYnMnDTnHnMnSExample: P3Y6M4DT12H30M5S(Means three years, six months, four days, twelve hours, thirty minutes, and five seconds)

Joda-Time classes can work with strings in both those formats, both as input (parsing) and output (generating strings).

Joda-Time performs comparisons using the Half-Open approach where the beginning of the span is inclusive while the ending is exclusive. This approach is a wise one for handling spans of time. Search StackOverflow for more info.

How to compare dates in Java? - Stack Overflow

java date comparison
Rectangle 27 18

LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) ) ;
Boolean isBetween = 
    ( ! today.isBefore( localDate1 ) )  // not-before is short for is-equal-to or later-than.
    &&
    today.isBefore( localDate3 ) ;

Half-open approach, where beginning is inclusive while ending is exclusive.

By the way, that is a bad choice of format for a text representation of a date or date-time value. Whenever possible, stick with the standard ISO 8601 formats. ISO 8601 formats are unambiguous, understandable across human cultures, and are easy to parse by machine.

For a date-only value, the standard format is YYYY-MM-DD. Note how this format has the benefit of being chronological when sorted alphabetically.

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

A time zone is crucial in determining a date. 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 Montral Qubec.

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );

As your input strings are non-standard format, we must define a formatting pattern to match.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" );

Use that to parse the input strings.

LocalDate start = LocalDate.parse( "22-02-2010" , f );
LocalDate stop = LocalDate.parse( "25-12-2010" , f );

In date-time work, usually best to define a span of time by the Half-Open approach where the beginning is inclusive while the ending is exclusive. So we want to know if today is the same or later than the start and also before the stop. A briefer way of saying is the same or later than the start is not before the start.

Boolean intervalContainsToday = ( ! today.isBefore( start ) ) && today.isBefore( stop ) ;

See the Answer by gstackoverflow showing the list of comparison methods you can call.

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.

  • Part of the standard Java API with a bundled implementation.
  • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

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.

UPDATE: This Joda-Time section below is left intact as history. The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

Other answers are correct with regard to the bundled java.util.Date and java.util.Calendar classes. But those classes are notoriously troublesome. So here's some example code using the Joda-Time 2.3 library.

If you truly want a date without any time portion and no time zone, then use the LocalDate class in Joda-Time. That class provides methods of comparison including compareTo (used with Java Comparators), isBefore, isAfter, and isEqual.

String string1 = "22-02-2010";
String string2 = "07-04-2010";
String string3 = "25-12-2010";

Define a formatter describing the input strings

DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd-MM-yyyy" );

Use formatter to parse the strings into LocalDate objects

LocalDate localDate1 = formatter.parseLocalDate( string1 );
LocalDate localDate2 = formatter.parseLocalDate( string2 );
LocalDate localDate3 = formatter.parseLocalDate( string3 );

boolean is1After2 = localDate1.isAfter( localDate2 );
boolean is2Before3 = localDate2.isBefore( localDate3 );
System.out.println( "Dates: " + localDate1 + " " + localDate2 + " " + localDate3 );
System.out.println( "is1After2 " + is1After2 );
System.out.println( "is2Before3 " + is2Before3 );
Dates: 2010-02-22 2010-04-07 2010-12-25
is1After2 false
is2Before3 true

So see if the second is between the other two (exclusively, meaning not equal to either endpoint)

boolean is2Between1And3 = ( ( localDate2.isAfter( localDate1 ) ) && ( localDate2.isBefore( localDate3 ) ) );

If you are working with spans of time, I suggest exploring in Joda-Time the classes: Duration, Interval, and Period. Methods such as overlap and contains make comparisons easy.

  • durationFormat: PnYnMnDTnHnMnSExample: P3Y6M4DT12H30M5S(Means three years, six months, four days, twelve hours, thirty minutes, and five seconds)

Joda-Time classes can work with strings in both those formats, both as input (parsing) and output (generating strings).

Joda-Time performs comparisons using the Half-Open approach where the beginning of the span is inclusive while the ending is exclusive. This approach is a wise one for handling spans of time. Search StackOverflow for more info.

How to compare dates in Java? - Stack Overflow

java date comparison
Rectangle 27 1

Did you want to adjust the time zone of the date-time to an Arab location such as Riyadh?

Did you want to localize the words used in the textual representation of a date-time, such as month and day name?

Did you want to localize the format of textual representation of a date-time, such as the order of presentation of day, month, year?

I'll just spin out a bit of example code using the Joda-Time 2.3 library, hoping it might help.

DateTime dateTimeUtc = new DateTime( DateTimeZone.UTC );

DateTimeZone timeZone = DateTimeZone.forID( "Asia/Riyadh" );
DateTime dateTimeRiyadh = dateTimeUtc.withZone( timeZone );

java.util.Locale locale = new Locale( "ar", "SA" ); // ( language code, country code );
DateTimeFormatter formatter = DateTimeFormat.forStyle( "FF" ).withLocale( locale ).withZone( timeZone );
String output = formatter.print( dateTimeUtc );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "dateTimeRiyadh: " + dateTimeRiyadh );
System.out.println( "output: " + output );
dateTimeUtc: 2014-02-16T09:52:33.901Z
dateTimeRiyadh: 2014-02-16T12:52:33.901+03:00
output: 16 , 2014 AST 12:52:33

spring - Java date time in arabic - Stack Overflow

java spring date internationalization arabic
Rectangle 27 1

Very easy to do in Joda-Time 2.3.

I suggest considering YYYY-MM-DD format because it sorts alphabetically chronologically. Joda-Time includes that ISO 8601 style format built-in. This format also makes it easier to parse later. And removes ambiguity about month vs day.

//  2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;

DateTime start = new DateTime( 2013, 2, 1, 12, 15 ).withTimeAtStartOfDay();
for ( int nthDay = 0; nthDay < 30; nthDay++ ) {
    DateTime dateTime = start.plusDays( nthDay ).withTimeAtStartOfDay();
    String fileName = ISODateTimeFormat.date().print( dateTime ) + ".dat";
    // create file in storage 
    System.out.println( "File # " + ( nthDay + 1 ) + ": " + fileName );
}

If you truly want the format in your question

DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd-MM-YYYY");
DateTime start = new DateTime( 2013, 2, 1, 12, 15 ).withTimeAtStartOfDay();
for ( int nthDay = 0; nthDay < 30; nthDay++ ) {
    DateTime dateTime = start.plusDays( nthDay ).withTimeAtStartOfDay();
    String fileName = formatter.print( dateTime ) + ".dat";
    // create file in storage 
    System.out.println( "File # " + ( nthDay + 1 ) + ": " + fileName );
}
File # 1: 01-02-2013.dat
File # 2: 02-02-2013.dat
File # 3: 03-02-2013.dat
File # 4: 04-02-2013.dat
File # 5: 05-02-2013.dat
File # 6: 06-02-2013.dat
File # 7: 07-02-2013.dat
File # 8: 08-02-2013.dat
File # 9: 09-02-2013.dat
File # 10: 10-02-2013.dat
File # 11: 11-02-2013.dat
File # 12: 12-02-2013.dat
File # 13: 13-02-2013.dat
File # 14: 14-02-2013.dat
File # 15: 15-02-2013.dat
File # 16: 16-02-2013.dat
File # 17: 17-02-2013.dat
File # 18: 18-02-2013.dat
File # 19: 19-02-2013.dat
File # 20: 20-02-2013.dat
File # 21: 21-02-2013.dat
File # 22: 22-02-2013.dat
File # 23: 23-02-2013.dat
File # 24: 24-02-2013.dat
File # 25: 25-02-2013.dat
File # 26: 26-02-2013.dat
File # 27: 27-02-2013.dat
File # 28: 28-02-2013.dat
File # 29: 01-03-2013.dat
File # 30: 02-03-2013.dat

java - How to name a file any days date using Calendar object - Stack ...

java date calendar
Rectangle 27 10

The answer by MadProgrammer is correct, especially the tip about Joda-Time. The successor to Joda-Time is now built into Java 8 as the new java.time package. Here's example code in Java 8.

When working with date-time (as opposed to local date), the time zone in critical. The day-of-month depends on the time zone. For example, the India time zone is +05:30 (five and a half hours ahead of UTC), while France is only one hour ahead. So a moment in a new day in India has one date while the same moment in France has yesterdays date. Creating string output lacking any time zone or offset information is creating ambiguity. You asked for YYYY-MM-DD output so I provided, but I don't recommend it. Instead of ISO_LOCAL_DATE I would have used ISO_DATE to get this output: 2014-02-25+05:30

ZoneId zoneId = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zonedDateTime = ZonedDateTime.now( zoneId );

DateTimeFormatter formatterOutput = DateTimeFormatter.ISO_LOCAL_DATE; // Caution: The "LOCAL" part means we are losing time zone information, creating ambiguity.
String output = formatterOutput.format( zonedDateTime );
System.out.println( "zonedDateTime: " + zonedDateTime );
System.out.println( "output: " + output );
zonedDateTime: 2014-02-25T14:22:20.919+05:30[Asia/Kolkata]
output: 2014-02-25

Similar code using the Joda-Time library, the precursor to java.time.

DateTimeZone zone = new DateTimeZone( "Asia/Kolkata" );
DateTime dateTime = DateTime.now( zone );
DateTimeFormatter formatter = ISODateTimeFormat.date();
String output = formatter.print( dateTime );

By the way, that format of your input string is a standard format, one of several handy date-time string formats defined by ISO 8601.

Both Joda-Time and java.time use ISO 8601 formats by default when parsing and generating string representations of various date-time values.

Calendar date to yyyy-MM-dd format in java - Stack Overflow

java date calendar converter
Rectangle 27 9

The answer by MadProgrammer is correct, especially the tip about Joda-Time. The successor to Joda-Time is now built into Java 8 as the new java.time package. Here's example code in Java 8.

When working with date-time (as opposed to local date), the time zone in critical. The day-of-month depends on the time zone. For example, the India time zone is +05:30 (five and a half hours ahead of UTC), while France is only one hour ahead. So a moment in a new day in India has one date while the same moment in France has yesterdays date. Creating string output lacking any time zone or offset information is creating ambiguity. You asked for YYYY-MM-DD output so I provided, but I don't recommend it. Instead of ISO_LOCAL_DATE I would have used ISO_DATE to get this output: 2014-02-25+05:30

ZoneId zoneId = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zonedDateTime = ZonedDateTime.now( zoneId );

DateTimeFormatter formatterOutput = DateTimeFormatter.ISO_LOCAL_DATE; // Caution: The "LOCAL" part means we are losing time zone information, creating ambiguity.
String output = formatterOutput.format( zonedDateTime );
System.out.println( "zonedDateTime: " + zonedDateTime );
System.out.println( "output: " + output );
zonedDateTime: 2014-02-25T14:22:20.919+05:30[Asia/Kolkata]
output: 2014-02-25

Similar code using the Joda-Time library, the precursor to java.time.

DateTimeZone zone = new DateTimeZone( "Asia/Kolkata" );
DateTime dateTime = DateTime.now( zone );
DateTimeFormatter formatter = ISODateTimeFormat.date();
String output = formatter.print( dateTime );

By the way, that format of your input string is a standard format, one of several handy date-time string formats defined by ISO 8601.

Both Joda-Time and java.time use ISO 8601 formats by default when parsing and generating string representations of various date-time values.

Calendar date to yyyy-MM-dd format in java - Stack Overflow

java date calendar converter
Rectangle 27 1

Maybe Noda Time is an option, John Skeet's .Net port of Joda-Time. The User Guide looks good and...I mean, he's known for good quality code ;)

c# - Well documented open source project in .net - Stack Overflow

c# .net open-source
Rectangle 27 298

Annoyingly, the withTimeAtStartOfDay answer is wrong, but only occasionally. You want:

Days.daysBetween(start.toLocalDate(), end.toLocalDate()).getDays()

It turns out that "midnight/start of day" sometimes means 1am (daylight savings happen this way in some places), which Days.daysBetween doesn't handle properly.

// 5am on the 20th to 1pm on the 21st, October 2013, Brazil
DateTimeZone BRAZIL = DateTimeZone.forID("America/Sao_Paulo");
DateTime start = new DateTime(2013, 10, 20, 5, 0, 0, BRAZIL);
DateTime end = new DateTime(2013, 10, 21, 13, 0, 0, BRAZIL);
System.out.println(daysBetween(start.withTimeAtStartOfDay(),
                               end.withTimeAtStartOfDay()).getDays());
// prints 0
System.out.println(daysBetween(start.toLocalDate(),
                               end.toLocalDate()).getDays());
// prints 1

Going via a LocalDate sidesteps the whole issue.

Can you provide an example case with specific data where you think Days.daysBetween is incorrect?

When you say to use Instant, you're not just talking about start.toInstant(), are you?

@PatrickM Yes, I was. On reflection, it's not clear exactly what constraints this is intended to impose, so I'll remove that last sentence. Thanks!

@chrispy daysBetween doc says it returns number of WHOLE days. In my case 2 days and 1 hour should return me 3 days. In your example it returns 2 days. Is there a way to achieve this?

java - Number of days between two dates in Joda-Time - Stack Overflow

java date jodatime
Rectangle 27 2

Java has always got inadequate support for the date and time use cases. For example, the existing classes (such as java.util.Date and SimpleDateFormatter) arent thread-safe which can lead to concurrency issues. Also there are certain flaws in API. For example, years in java.util.Date start at 1900, months start at 1, and days start at 0not very intuitive. These issues led to popularity of third-party date and time libraries, such as Joda-Time. To address a new date and time API is designed for Java SE 8.

LocalDateTime timePoint = LocalDateTime.now();
System.out.println(timePoint);

The method now() returns the current date-time using the system clock and default time-zone, not null. It obtains the current date-time from the system clock in the default time-zone. This will query the system clock in the default time-zone to obtain the current date-time. Using this method will prevent the ability to use an alternate clock for testing because the clock is hard-coded.

Equivalent of C#'s DateTime.Now in Java? - Stack Overflow

java datetime
Rectangle 27 2

Java has always got inadequate support for the date and time use cases. For example, the existing classes (such as java.util.Date and SimpleDateFormatter) arent thread-safe which can lead to concurrency issues. Also there are certain flaws in API. For example, years in java.util.Date start at 1900, months start at 1, and days start at 0not very intuitive. These issues led to popularity of third-party date and time libraries, such as Joda-Time. To address a new date and time API is designed for Java SE 8.

LocalDateTime timePoint = LocalDateTime.now();
System.out.println(timePoint);

The method now() returns the current date-time using the system clock and default time-zone, not null. It obtains the current date-time from the system clock in the default time-zone. This will query the system clock in the default time-zone to obtain the current date-time. Using this method will prevent the ability to use an alternate clock for testing because the clock is hard-coded.

Equivalent of C#'s DateTime.Now in Java? - Stack Overflow

java datetime
Rectangle 27 44

Use this situation carefully because the it may throw an exception when the time shift if you are using it in a Daylight savings configured environment. If you have the date in text you may prefer a solution like this stackoverflow.com/questions/5451152/

java - In joda time how to convert time zone without changing time - S...

java datetime jodatime
Rectangle 27 624

In addition to the already mentioned <pre> tags, you should also use the @code JavaDoc annotation, which will make life much easier when it comes to HTML entities issues (in particular with Generics), e.g.:

* <pre>
* {@code
* Set<String> s;
* System.out.println(s);
* }
* </pre>
Set<String> s;
System.out.println(s);

While omitting the @code block (or using a <code> tag) will result in HTML like this:

Set s;
System.out.println(s);

I would have thought so too, but unfortunately it doesn't, you still need to add the <pre> tag to get line breaks.

Unfortunately, it seems when you hit ctrl+shift+F (Format code in Eclipse), Eclipse messes up the {@code} tag and replaces it with {code ...

@jpdaigle I just tried this in Eclipse Galileo and Helios and the formatter does not replace anything for me (on Mac OS, but I have never seen the formatter do anything like that on other platforms either).

Another unfortunate, if you have blocks in your example code using curly braces "{}", the first closing brace will terminate the @code block. One way around it is to use (wait for it...) html entities for the braces. I don't see a compelling argument for <pre> tags for code with blocks.

java - Multiple line code example in Javadoc comment - Stack Overflow

java html javadoc
Rectangle 27 610

In addition to the already mentioned <pre> tags, you should also use the @code JavaDoc annotation, which will make life much easier when it comes to HTML entities issues (in particular with Generics), e.g.:

* <pre>
* {@code
* Set<String> s;
* System.out.println(s);
* }
* </pre>
Set<String> s;
System.out.println(s);

While omitting the @code block (or using a <code> tag) will result in HTML like this:

Set s;
System.out.println(s);

I would have thought so too, but unfortunately it doesn't, you still need to add the <pre> tag to get line breaks.

Unfortunately, it seems when you hit ctrl+shift+F (Format code in Eclipse), Eclipse messes up the {@code} tag and replaces it with {code ...

@jpdaigle I just tried this in Eclipse Galileo and Helios and the formatter does not replace anything for me (on Mac OS, but I have never seen the formatter do anything like that on other platforms either).

Another unfortunate, if you have blocks in your example code using curly braces "{}", the first closing brace will terminate the @code block. One way around it is to use (wait for it...) html entities for the braces. I don't see a compelling argument for <pre> tags for code with blocks.

java - Multiple line code example in Javadoc comment - Stack Overflow

java html javadoc