I want to get the difference between two Java Date objects. I've used Joda-Time library. But the problem is that I'm getting the Days greater difference than that of actual day difference.
Here's my code snippet:
DateFormat formatter = new SimpleDateFormat("mm/dd/yyyy");
Date someDate=new Date();
Date today = Calendar.getInstance().getTime();
try {
someDate = formatter.parse("06/22/2010");
}
catch(ParseException pe) {
System.out.println("Parser Exception");
}
int days = Days.daysBetween(new DateTime(someDate), new DateTime(today)).getDays();
System.out.println(" Days Between " + someDate + " : " + today + " - " + days);
Here's my output:
Days Between Fri Jan 22 00:06:00 IST 2010 : Sun Jul 25 19:27:01 IST 2010 - 184
Here, Why does it takes "06/22/2010" as Jan 22? Does anyone face similar problem?
Help me friends.. Thanx in advance..
It seems like mm refers to minutes, not months, which is MM. Please check here to see the list of appropriate lettering :)
Month is MM
In your case:
DateFormat formatter = new
SimpleDateFormat("MM/dd/yyyy");
Your pattern is slightly defective. mm is parsed as minutes in hour, you're looking for MM which is month of year.
mm => minutes, not months - you need MM for months - that'll resolve your Jan problem!
The other answers correctly solved your specific problem.
LocalDate
But there is a larger solution. If you are starting with only dates, no time-of-day and no time zones, then you should be using the LocalDate class rather than DateTime.
Time Zone
Your code ignores the crucial issue of time zones. Time zones matter even for LocalDate, when trying to determine "today". Do you want today's date in Montréal or in Paris. A new day dawns in Paris earlier. When you omit time zone, you get the JVM’s current default time zone.
Joda-Time Can Parse
Furthermore, let Joda-Time do the parsing. No need to be using java.util.Date & .Calendar at all. Joda-time's formatting characters are almost the same as java.util.Date but not entirely so be sire to consult the doc. In this case it it identical.
DateTimeFormatter formatter = DateTimeFormat.forPattern( "MM/dd/yyyy" );
LocalDate past = formatter.parseLocalDate( "06/22/2010" );
DateTimeZone = DateTimeZone.forID( "America/Montreal" ): // match time zone intended for that input string.
int days = Days.daysBetween( past, LocalDate.now( timeZone ) );
Related
How can I convert time from unix timestamp to week day? For example, I want to convert 1493193408 to Wednesday.
I tryed code above, but It always shows Sunday..
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date dateFormat = new java.util.Date(1493193408);
String weekday = sdf.format(dateFormat );
Using java.time
The other Answers use the troublesome old date-time classes, now legacy, supplanted by the java.time classes.
Time zone is crucial in determining a date, and therefore getting a day-of-week.
Get an Instant from your count of while seconds since the epoch of 1970 in UTC. Apply a time zone to get a ZonedDateTime. From there extract a DayOfWeek enumerate object. Ask that object to automatically localize to generate a string of its name.
Instant.ofEpochSecond( 1_493_193_408L )
.atZone( ZoneId.of( "America/Montreal" ))
.getDayOfWeek()
.getDisplayName( TextStyle.FULL , Locale.US )
For Android, see the ThreeTenABP project for a back-port of most of the java.time functionality.
You need to multiply it by 1000 since Java and Unix time are not the same.
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date dateFormat = new java.util.Date(1493193408L * 1000);
String weekday = sdf.format(dateFormat );
You can use a calendar instance because it provides you methods for getting that information:
Date date = new Date(1493193408000L);
Calendar c = Calendar.getInstance();
c.setTime(date);
System.out.println(c.get(Calendar.DAY_OF_WEEK));
System.out.println(c.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.US));
The Date constructor has the following description:
Allocates a Date object and initializes it to represent the specified
number of milliseconds since the standard base time known as "the
epoch", namely January 1, 1970, 00:00:00 GMT.
Your timestamp is in seconds, if you multiply by 1000 (to get milliseconds) you get the expected answer:
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date dateFormat = new java.util.Date(1493193408000L);
System.out.println(dateFormat);
String weekday = sdf.format(dateFormat);
System.out.println(weekday);
Which prints
Wed Apr 26 09:56:48 CEST 2017
Wednesday
dateFormatStart != dateFormat
You could also check using:
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date dateFormat = new Date(System.currentTimeMillis());
String weekday = sdf.format(dateFormat);
Here is right code for you:
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date dateFormat = new java.util.Date(1493193408 * 1000);
String weekday = sdf.format(dateFormat );
There is documentation for Java date
You can do the same with the new JDK 8 date time classes. Local date and time is calculated using the seconds from Unix Epoch and then it can be formatted with a specific pattern. The conversion to date time takes into account the Zone as well, I have used the default Zone, but it can be modified to use a specific zone.
ZonedDateTime ldt = ZonedDateTime.ofInstant(Instant.ofEpochSecond(1493193408), ZoneId.systemDefault());
System.out.println(ldt.format(DateTimeFormatter.ofPattern("EEEE")));
It’s been said already: your problem is your are feeding number seconds since the Unix epoch into a Date when it expects the number of milliseconds (then one would have expected multiplying by 1000 to be simple, but a couple of the other answers got that part wrong).
If you are going to work with dates, times or weekdays in your app, I agree with the answers that recommend that you consider the newer classes in java.time. They are much nicer to work with. Your code will more directly express your intent.
But if you only need the weekday, a dependency on a third party library may be overkill. I still recommend keeping a distance to the oldfashioned classes SimpleDateFormat, Date and Calendar, though. Is there a third option? There certainly is! A simple oneliner, even:
String weekday = String.format(Locale.ENGLISH, "%tA", 1493193408 * 1000L);
This yields Wednesday as desired. You must still be aware that the result depends on your computer’s time zone setting, though.
I have a timestamp that I am trying to put into a Date object, however when I use Calendar, I am running into a strange problem. I seem to be able to unable to create a Date object with the values I want:
public static void main(String args[]){
Date today = new Date();
int hour = 4, min=0, sec=0, ms=64;
Calendar cal = GregorianCalendar.getInstance();
cal.clear();
cal.setTimeZone(TimeZone.getTimeZone("EDT"));
cal.setTime(today);
cal.set(Calendar.HOUR_OF_DAY,hour);
cal.set(Calendar.MINUTE,min);
cal.set(Calendar.SECOND,sec);
cal.set(Calendar.MILLISECOND,ms);
System.out.println("Time is: "+cal.getTime());
}
This produces:
Time is: Mon Jan 13 23:00:00 EST 2014
which is not the result I am looking for.
However, if I comment out the 'setTimeZone' method call, I get the following result:
Time is: Tue Jan 14 04:00:00 EST 2014
This is the result that I am looking for but I am concerned that if I am running on a machine that is not running in the same time zone, I will not get consistent behavior.
This is the result that I am looking for but I am concerned that if I am running on a machine that is not running in the same time zone
it is the problem. The internal representation should be ok, but it prints on local timezone: representation differs from real content.
use SimpleDateFormat http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html and set TimeZone to see the date on the Zone desired.
The problem here is that Java does not know of the timezone "EDT" (Eastern Daylight Time). As a result, Calendar seems to be setting the timezone to GMT.
The timezone needed here is "America/New_York" or "EST5EDT". When either of these values are used, the correct result is produced.
The list of valid Time Zones can be obtained by calling TimeZone.getAvailableIDs()
It is unfortunate that no warnings are produced when the requested Time Zone is not found.
If you can do away with java.util.Date, you can use joda time API to conveniently set these values as desired:
For your query, you can set your already created Calendar instance as a constructor parameter to DateTime.
DateTime dt = new DateTime(cal);
System.out.println(dt.toDateTimeISO());
Output:
2014-01-14T04:00:00.064-05:00
Calendar.getTime() returns a java.util.Date object. Date objects do not know anything about timezones. The Date object that Calendar.getTime() returns does not know to what timezone the Calendar that it came from is set.
When you print a Date object (for example, by implicitly calling toString() object, as you are doing) it is formatted in the default time zone of the machine you are running it on.
If you want to print a Date in a specific timezone, use a SimpleDateFormat, and set the desired timezone on the SimpleDateFormat object. For example:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
df.setTimeZone(TimeZone.getTimeZone("EDT"));
// Will display the date that the calendar is set to in the EDT timezone
System.out.println(df.format(cal.getTime()));
Java Date objects represent the number of milliseconds seconds since January 1, 1970, 00:00:00 GMT due to the fact that the other methods are deprecated. The two ways to "view" a Date object directly are "getTime()" and "toString()" (using "dow mon dd hh:mm:ss zzz yyyy"). Therefore, you are formatting the GMT value to your local timezone.
When working with dates, it is best to think of them as GMT values, and then as a "formatting" exercise when viewing the date.
For comparison, here is that same kind of code but using Joda-Time 2.3.
Avoid the java.util.Date & .Calendar classes.
Never use three-letter codes for time zones. They are neither standardized nor unique. Instead use proper time zone names. In this case, use "America/New_York" or "America/Montreal".
// Use time zone names, such as from this slightly outdated list: http://joda-time.sourceforge.net/timezones.html
DateTimeZone timeZone = DateTimeZone.forID( "America/New_York" );
// Input.
int hour = 4, min = 0, sec = 0, ms = 64;
// Start with now, then adjust the time of day.
DateTime now = new DateTime( timeZone );
DateTime dateTime = now.withHourOfDay( hour ).withMinuteOfHour( min ).withSecondOfMinute( sec ).withMillisOfSecond( ms );
// If needed, translate to a java.util.Date for use with other classes.
java.util.Date date = dateTime.toDate();
Dump to console…
System.out.println( "now: " + now );
System.out.println( "dateTime: " + dateTime );
System.out.println( "date: " + date );
When run…
now: 2014-01-20T21:04:51.237-05:00
dateTime: 2014-01-20T04:00:00.064-05:00
date: Mon Jan 20 01:00:00 PST 2014
When I try to print the current date and time using Calender instance, the result I get is 1 hour ahead from the actual time.
I am working in remote machine which runs with EST time zone. Below is what I tried, but nothing works.
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("EST"));
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
System.out.println("Current Date & Time: " +calendar.getTime());
o/p:
Time: Sat Dec 28 11:55:10 UTC 2013
But expected o/p:
Time: Sat Dec 28 10:55:10 UTC 2013
All the 3 types give same result. I couldn't understand what I miss out to get the exact date & time. Is this problem related to daylight time saving ?
Could someone help me to overcome this problem. Thanks in Advance.
It is again this old pitfall with java.util.Date: Its toString()-method which you indirectly use when printing calendar.getTime() uses your default time zone, not the time zone of your calendar instance (which you set to 'EST').
Solution:
Date currentTime = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
System.out.println("Current Date & Time: " + sdf.format(currentTime));
Explanations:
a) In first line no calendar instance is necessary because you are just interested in current global time (the same physical time independent from timezone). Calendar.getInstance() is also more consuming resources. Finally, both expressions new Date() and Calendar.getInstance(...).getTime() have no time zone reference when it is about the internal state. Only the toString()-method of j.u.Date uses default time zone.
b) You need to define an output format which is given in line 2. It is up to you to change it. Just study the pattern documentation of java.text.SimpleDateFormat.
c) You also need to define the time zone in your output format to help the format object to translate the global Date-instance into a timezone-aware representation. By the way, I had choosen the identifier 'America/New_York', not 'EST' because latter form can be sometimes ambigous. You should either choose the first form (IANA- or Olson time zone identifier) or the form 'GMT+/-HH:mm'.
d) The output itself is done with sdf.format(currentTime), not just currentTime (no implicit call of toString()).
e) To answer your question 'Is this problem related to daylight time saving ?': No, the time in time zone EST (America/New_York) is never in DST in december.
Conclusion:
If you can, you should try to avoid j.u.Date and j.u.Calendar because there are too many pitfalls. At the moment JodaTime is a better alternative, although not without issues.
Avoid 3-Letter Time Zone
Never use the 3-letter time zone codes. They are neither standardized nor unique. Your "EST" can mean at least these:
Eastern Standard Time (USA)
Eastern Standard Time (Australia)
Eastern Brazil Standard Time
Use time zone names.
Avoid j.u.Date/Calendar
You have discovered one of the many reasons to avoid using java.util.Date & java.util.Calendar classes bundled with Java: A Date instance has no time zone information yet its toString method confusingly renders a string based on your Java environment's default time zone.
Use Joda-Time
Use a competent date-time library. In Java that means either Joda-Time, or in Java 8, the new java.time.* classes (inspired by Joda-Time).
Example code…
// Default time zone
DateTime dateTime_MyDefaultTimeZone = new DateTime();
// Specific time zone. If by "EST" you meant east coast of United States, use a name such as New York.
DateTimeZone timeZone = DateTimeZone.forID( "America/New_York" );
DateTime dateTime_EastCoastUS = new DateTime( timeZone );
Dump to console…
System.out.println( "dateTime_MyDefaultTimeZone: " + dateTime_MyDefaultTimeZone );
System.out.println( "dateTime_EastCoastUS: " + dateTime_EastCoastUS );
System.out.println( "date-time in UTC: " + dateTime_EastCoastUS.toDateTime( DateTimeZone.UTC ) );
When run…
dateTime_MyDefaultTimeZone: 2013-12-28T18:51:18.485-08:00
dateTime_EastCoastUS: 2013-12-28T21:51:18.522-05:00
date-time in UTC: 2013-12-29T02:51:18.522Z
This question already has answers here:
How to subtract n days from current date in java? [duplicate]
(5 answers)
Closed 7 years ago.
I'm trying to subtract 5 days from a date which comes in as a string initially.
I have had a look at some of the other posts on this subject but the result i get from the code is always incorrect. The main problem is that the year value does not seem to change when the days are subtracted for example - 2012-01-01 subtract 5 days gives me 'Jan 27 2012' using this code -
cal.add(Calendar.DATE, -5);
Please help.
Did you know that, in Java, month 1 is actually February?
Date februaryTheFirst = new Date(2012,1,1); // equals 2012-02-01
This might explain what you are seeing. If you want to instantiate 2012-01-01 instead, you should do:
Date firstDayOf2012 = new Date(2012,0,1); // this is 2012-01-01
Exactly the same thing happens when dealing with Calendar:
Calendar.getInstance().set(2012,0,1); // 2012-01-01
Be sure to check the documentation for Date(int, int, int) and Calendar.set(int, int, int). Also, you could check the way you are parsing the string. If you use SimpleDateFormat.parse(...), things can be easier.
Strange, isn't it? Go figure... Just as a fun fact, IntelliJ's documentation annotates this second parameter, month, with #MagicConstant, to remember the programmer that there's something very strange going on.
Calendar.FEBRUARY is 1 and five days before 1 Feb 2012 was 27 Jab 2012.
Your implementation is correct and you are getting the correct value aslo.
Calendar's Months started with 0
0 = Jan
1 = Feb
so subtracting 5 days from 2012-01-01 will definitely returns you Jan 27 2012
something is here also which will helps you Why is January month 0 in Java Calendar?
Joda-Time
The Joda-Time 2.7 library makes this work much easier. Just call the minusDays method.
String input = "2012-01-01";
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTime = new DateTime( input, zone );
DateTime then = now.minusDays( 5 );
DateTimeFormatter formatter = DateTimeFormat.forStyle( "FF" ).withZone( zone ).withLocale( Locale.CANADA_FRENCH );
String output = formatter.print( then );
If you want the beginning of the day, add a call to withTimeAtStartOfDay. This is unnecessary in your case, when parsing a date-only string with no time-of-day.
DateTime dateTimeAtStartOfDay = new DateTime( input, zone ).withTimeAtStartOfDay();
If you want only date without time-of-day or time zone, use LocalDate instead of DateTime.
LocalDate then = new LocalDate( "2012-01-01" ).minusDays( 5 );
If you need to convert to the old java.util.Date, call toDate on the DateTime.
java.time
Java 8 has a new package, java.time. These new classes were inspired by Joda-Time but were re-architected. Both java.time and Joda-Time can solve this particular problem equally well.
Use:
cal.add(Calendar.DAY_OF_MONTH, -5)
EDIT: sorry. DAY_OF_MONTH is a synonym to DATE. Instead of 1 use Calendar.JANUARY.
This a segment of code that is working on my pc. first you have to get the calendar instance the perform your calculation.
Calendar cal = Calendar.getInstance();
System.out.println("Today : " + cal.getTime());
// Subtract 300 days from the calendar
cal.add(Calendar.DATE, -300);
System.out.println("300 days ago: " + cal.getTime());
This is the output that you will get:
Today : Wed Oct 17 10:41:23 EET 2012
300 days ago: Thu Dec 22 10:41:23 EET 2011
I have the following problem using Joda-Time for parsing and producing date and time around Daylight Saving Time (DST) hours. Here is an example (please, note that March 30th 2008 is Daylight Saving change in Italy):
DateTimeFormatter dtf = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
DateTime x = dtf.parseDateTime("30/03/2008 03:00:00");
int h = x.getHourOfDay();
System.out.println(h);
System.out.println(x.toString("dd/MM/yyyy HH:mm:ss"));
DateTime y = x.toDateMidnight().toDateTime().plusHours(h);
System.out.println(y.getHourOfDay());
System.out.println(y.toString("dd/MM/yyyy HH:mm:ss"));
I get the following output:
3
30/03/2008 03:00:00
4
30/03/2008 04:00:00
When i parse hour I get hour is 3. In my data structure I save the day storing midnight time, and then I have some value for each hour of the day (0-23). Then, when I write out the date, I re-compute the full date time making midnight plus hour. When I sum 3 hours to my midnight I get 04:00:00! And if I parse it again, I get hour 4!
Where is my mistake? Is there some way to get hour 2 when I parse or get hour three when I print out?
I have also tried to build output by hand:
String.format("%s %02d:00:00", date.toString("dd/MM/yyyy"), h);
but in this case for hour 2, I produce 30/03/2008 02:00:00 which is not a valid date (since hour 2 does not exist) and cannot be parsed any more.
Thank you in advance for your help.
Filippo
When I sum 3 hours to my midnight I get 04:00:00! And if I parse it again, I get hour 4! Where is my mistake?
You mentioned already that this date is exactly when the time changes. So there is no mistake. March 30, 2010 00:00 CEST (the timezone in Italy) is precisely speaking March 29, 2010 23:00 UTC. When you add 3 hours, you will get March 30, 2010 02:00 UTC. But this is post the moment, that we switch times (which happens on 01:00 UTC), so when you convert time to local timezone you get March 30, 04:00. That's correct behavior.
Is there some way to get hour 2 when I parse or get hour three when I print out?
No, because March 30, 2010 02:00 CEST does not exist. Precisely at March 30, 2010 01:00 UTC we switch time from +1 hour to +2 hours versus UTC, so March 30, 2010 00:59 UTC is March 30, 2010: 01:59 CEST, but March 30, 2010 01:00 UTC become March 30, 2010 03:00 CEST. No 02:xx hour exist on that particular date.
BTW. In a week you can expect another "fun". Can you tell what date in UTC this refers to:
October 31, 2010 02:15 CEST ?
Well, the funny part is, we do not know. It could be either 0ctober 31, 2010 00:15 UTC (before actual time switch) or October 31, 2010 01:15 UTC (after the switch).
That's exactly why you should always store date and times in relation to UTC and convert them to local time zone before displaying, otherwise you risk an ambiguity.
HTH.
The data structure you are saving your data is not very optimal for the days with daylight saving time. Your day in this particular day should only have 23 hours.
If you do:
DateTimeFormatter dtf = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss").withLocale(Locale.US);
DateTime x = dtf.parseDateTime("30/03/2008 00:00:00");
DateTimeFormatter parser = DateTimeFormat.fullDateTime();
System.out.println("Start:"+parser.print(x));
DateTime y = x.plusHours(4);
System.out.println("After add of 4:"+parser.print(y));
You get the expected result, that the time is 05:00.
I recommend that you change the way you store your day and use a date. If not, you must handle daylight saving time when storing the hour of day.
You might do something like this:
In the case where we move the time forward one hour, as this case, you must store 4 and not 5 as the time for 5. And when you calculate the time, you should use the plusHours() method to get the actual time. I think you might get away with something like:
public class DateTest {
private static final int HOUR_TO_TEST = 2;
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
DateTime startOfDay = dtf.parseDateTime("30/03/2008 00:00:00");
/* Obtained from new DateTime() in code in practice */
DateTime actualTimeWhenStoring = startOfDay.plusHours(HOUR_TO_TEST);
int hourOfDay = actualTimeWhenStoring.getHourOfDay();
int hourOffset = startOfDay.plusHours(hourOfDay).getHourOfDay();
System.out.println("Hour of day:" + hourOfDay);
System.out.println("Offset hour:" + hourOffset);
int timeToSave = hourOfDay;
if (hourOffset != hourOfDay) {
timeToSave = (hourOfDay + (hourOfDay - hourOffset));
}
System.out.println("Time to save:" + timeToSave);
/* When obtaining from db: */
DateTime recalculatedTime = startOfDay.plusHours(timeToSave);
System.out.println("Hour of time 'read' from db:" + recalculatedTime.getHourOfDay());
}
}
...or basicly something like that. I'd write a test for it if you choose for going down this route. You can change the HOUR_TO_TEST to see that it moves passed the daylight saving time.
Building on the correct answers by Paweł Dyda & Knubo…
ISO 8601 For String Format
You should never store (serialize) a date-time as a string in the format you mentioned: "30/03/2008 03:00:00". Problems:
Omitted time zone.
Day, Month, Year order is ambiguous.
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
No Midnight
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.
Example Code in Joda-Time 2.3
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 );
When run:
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