Get Canada/Eastern offset from input ISTdate and time - java

i want to get Canada/Eastern offset value from IST input date
e.g if i input 2016-03-10 10:01 then system return correct Offset is -05:00 Canada/Eastern
but when i input 2020-05-28 10:00 then i want Offset is -04:00 Canada/Eastern
thank you in adavance
public class TimeZoneConversation {
private static final String DATE_FORMAT = "yyyy-M-dd HH:mm";
static ZoneId istZoneId = ZoneId.of("Asia/Kolkata");
static ZoneId etZoneId = ZoneId.of("Canada/Eastern");
public static void main(String[] args) {
String dateInString = "2020-02-28 10:00";
LocalDateTime currentDateTime = LocalDateTime.parse(dateInString, DateTimeFormatter.ofPattern(DATE_FORMAT));
ZonedDateTime currentISTime = currentDateTime.atZone(istZoneId); //India Time
ZonedDateTime currentETime = currentISTime.withZoneSameInstant(etZoneId); //EST Time
System.out.println(currentISTime.toLocalDate() + " " + currentISTime.toLocalTime() + " IST");
System.out.println(currentETime.toLocalDate() + " " + currentETime.toLocalTime() + " EST/Canada");
Instant instant = Instant.now(); // Capture current moment in UTC.
ZonedDateTime canadaTime = instant.atZone(etZoneId);
System.out.println("Offset is " + canadaTime.getOffset() + " " + etZoneId);
}
}
//output of above program
2020-02-28 10:00IST
2020-02-27 23:30 EST/Canada
Offset is -05:00 Canada/Eastern

I don't think you should retrieve the offset from the Instant object. The right way should be to retrieve the offset from ZonedDateTime.
Here is a good explanation for Instant, LocalDateTime and ZonedDateTime: What's the difference between Instant and LocalDateTime?
A working solution for your problem:
// ...
LocalDateTime currentDateTime = LocalDateTime.parse(dateInString, DateTimeFormatter.ofPattern(DATE_FORMAT));
ZonedDateTime currentISTime = currentDateTime.atZone(istZoneId); //India Time
ZonedDateTime currentETime = currentISTime.withZoneSameInstant(etZoneId); //EST Time
System.out.println(currentISTime.toLocalDate() + " " + currentISTime.toLocalTime() + " IST");
System.out.println(currentETime.toLocalDate() + " " + currentETime.toLocalTime() + " EST/Canada");
// apply getOffset() on ZonedDateTime, not on Instant
System.out.println("Offset is " + currentETime.getOffset() + " " + etZoneId);
Output for 2016-03-10 10:01 is Offset is -05:00 Canada/Eastern
Output for 2020-05-28 10:00 is Offset is -04:00 Canada/Eastern

Related

Change date and time to UTC format

I have input date and time "2021-05-03T15:46:09.354+08:00"
I want UTC format output - "2021-05-03T07:46:09.354Z"
Any Idea and suggestion
Input string fits an OffsetDateTime and output string fits an Instant, so:
Instant instant = OffsetDateTime.parse("2021-05-03T15:46:09.354+08:00").toInstant();
System.out.println(instant); // prints: 2021-05-03T07:46:09.354Z
You can also use ZonedDateTime and the result can be also be OffsetDateTime or ZonedDateTime.
ZonedDateTime inZoned = ZonedDateTime.parse("2021-05-03T15:46:09.354+08:00");
ZonedDateTime outZoned = inZoned.withZoneSameInstant(ZoneOffset.UTC);
System.out.println(inZoned + " -> " + outZoned);
// prints: 2021-05-03T15:46:09.354+08:00 -> 2021-05-03T07:46:09.354Z
OffsetDateTime inOffset = inZoned.toOffsetDateTime();
OffsetDateTime outOffset = inOffset.withOffsetSameInstant(ZoneOffset.UTC);
System.out.println(inOffset + " -> " + outOffset);
// prints: 2021-05-03T15:46:09.354+08:00 -> 2021-05-03T07:46:09.354Z
Dont have enough reputation to comment, but have you tried using the Instant class in Java? Link to javadoc. The parse() might be able to help, then you can call toString() on the Instant.
https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html
https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html#parse-java.lang.CharSequence-
public static void main(String[] args) throws Exception
{
DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter
.ofPattern("dd-MM-uuuu'T'HH:mm:ss:SSSXXXXX");
//Date string with offset information
String dateString = "03-08-2019T16:20:17:717+05:30";
System.out.println("input date: "+dateString);
//Instance with given offset
OffsetDateTime odtInstanceAtOffset = OffsetDateTime.parse(dateString, DATE_TIME_FORMATTER);
//Instance in UTC
OffsetDateTime odtInstanceAtUTC = odtInstanceAtOffset.withOffsetSameInstant(ZoneOffset.UTC);
//Formatting to string
String dateStringInUTC = odtInstanceAtUTC.format(DATE_TIME_FORMATTER);
//Convert OffsetDateTime to instant which is in UTC
System.out.println("expected date :"+odtInstanceAtOffset.toInstant());
}
ouput:
input date: 03-08-2019T16:20:17:717+05:30
expected date :2019-08-03T10:50:17.717Z

Format calendar date to dd-MM-yyyy affected by timezone

I got a huge problem with converting my calendar objects to readable strings.
Actually I use df.format(cal.getTime()) to get a formatted string, this is not working quite well, because the Date object I get from cal.getTime() is not affected by timezones.
Please bite back any comments like "use joda time"...
I´m looking for a solution to convert directly from calendar objects to string.
These are my formatters:
private DateFormat df = new SimpleDateFormat("HH:mm", Locale.GERMANY); // 13:42 Uhr
private DateFormat df2 = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.GERMANY); // 14.04.2012
If you guys give this code a try, you will see that Date objects are not affected by timezones.
// this date is at wintertime
long milli = 1445945400000l; // CET - central european time
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(milli);
System.out.println(" ");
System.out.println("Kalender setTimeInMillis(" + milli + ");");
System.out.println("Daylight Time ? = " + cal.getTimeZone().useDaylightTime());
System.out.println("Date Time = " + cal.getTime());
System.out.println("Kalender Tag = " + cal.get(Calendar.DATE) + " Monat = " + (cal.get(Calendar.MONTH) + 1) + " Jahr = " + cal.get(Calendar.YEAR));
System.out.println("Kalender Uhrzeit = " + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + ":" + cal.get(Calendar.SECOND));
cal.setTimeZone(TimeZone.getTimeZone("Europe/Berlin"));
System.out.println(" ");
System.out.println("Kalender setTimeZone(TimeZone.getTimeZone(\"Europe/Berlin\");");
System.out.println("Daylight Time ? = " + cal.getTimeZone().useDaylightTime());
System.out.println("Date Time = " + cal.getTime());
System.out.println("Kalender Tag = " + cal.get(Calendar.DATE) + " Monat = " + (cal.get(Calendar.MONTH) + 1) + " Jahr = " + cal.get(Calendar.YEAR));
System.out.println("Kalender Uhrzeit = " + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + ":" + cal.get(Calendar.SECOND));
// this date is at summertime
long milliS = 1445609700000l; // CEST - central european summertime
Calendar calS = Calendar.getInstance();
calS.setTimeInMillis(milliS);
System.out.println(" ");
System.out.println("Kalender setTimeInMillis(" + milliS + ");");
System.out.println("Daylight Time ? = " + calS.getTimeZone().useDaylightTime());
System.out.println("Date Time = " + calS.getTime());
System.out.println("Kalender Tag = " + calS.get(Calendar.DATE) + " Monat = " + (calS.get(Calendar.MONTH) + 1) + " Jahr = " + calS.get(Calendar.YEAR));
System.out.println("Kalender Uhrzeit = " + calS.get(Calendar.HOUR_OF_DAY) + ":" + calS.get(Calendar.MINUTE) + ":" + calS.get(Calendar.SECOND));
calS.setTimeZone(TimeZone.getTimeZone("Europe/Berlin"));
System.out.println(" ");
System.out.println("Kalender setTimeZone(TimeZone.getTimeZone(\"Europe/Berlin\");");
System.out.println("Daylight Time ? = " + calS.getTimeZone().useDaylightTime());
System.out.println("Date Time = " + calS.getTime());
System.out.println("Kalender Tag = " + calS.get(Calendar.DATE) + " Monat = " + (calS.get(Calendar.MONTH) + 1) + " Jahr = " + calS.get(Calendar.YEAR));
System.out.println("Kalender Uhrzeit = " + calS.get(Calendar.HOUR_OF_DAY) + ":" + calS.get(Calendar.MINUTE) + ":" + calS.get(Calendar.SECOND));
OUTPUT
Kalender setTimeInMillis(1445945400000);
Daylight Time ? = false
Date Time** = Tue Oct 27 11:30:00 GMT 2015
Kalender Tag = 27 Monat = 10 Jahr = 2015
Kalender Uhrzeit = 11:30:0
Kalender setTimeZone(TimeZone.getTimeZone("Europe/Berlin");
Daylight Time ? = true
Date Time = Tue Oct 27 11:30:00 GMT 2015
Kalender Tag = 27 Monat = 10 Jahr = 2015
Kalender Uhrzeit = 12:30:0
Kalender setTimeInMillis(1445609700000);
Daylight Time ? = false
Date Time = Fri Oct 23 14:15:00 GMT 2015
Kalender Tag = 23 Monat = 10 Jahr = 2015
Kalender Uhrzeit = 14:15:0
Kalender setTimeZone(TimeZone.getTimeZone("Europe/Berlin");
Daylight Time ? = true
Date Time = Fri Oct 23 14:15:00 GMT 2015
Kalender Tag = 23 Monat = 10 Jahr = 2015
Kalender Uhrzeit = 16:15:0
You need to set the time zone of the formatter, a quick example:
SimpleDateFormat df = new SimpleDateFormat();
Calendar cal1 = Calendar.getInstance(TimeZone.getTimeZone("GMT+4:00"));
df.setTimeZone(cal1.getTimeZone());
System.out.println(df.format(cal1.getTime()));
Calendar cal2 = Calendar.getInstance(TimeZone.getTimeZone("GMT-3:00"));
df.setTimeZone(cal2.getTimeZone());
System.out.println(df.format(cal2.getTime()));
Output:
10/30/15 1:02 PM
10/30/15 6:02 AM
Be aware that java.util.Date objects do not contain any timezone information by themselves - you cannot set the timezone on a Date object. The only thing that a Date object contains is a number of milliseconds since the "epoch" - 1 January 1970, 00:00:00 UTC.
See https://stackoverflow.com/a/2892156/5445351
Date Has Its Own Time Zone
Confusingly, a java.util.Date is assigned an internal time zone using the JVM's current default time zone. You cannot get or set that zone. The java.util.Calendar class was added to Java to handle time zone and other such issues.
Count From Epoch
long milli = 1445945400000l; // CET - central european time
Usually a number like that is a count-from-epoch in UTC (GMT), not any particular time zone. After creating a date-time object from that number you then assign a time zone to be applied.
Tip: Use an uppercase L on an integer literal to avoid looking like a 1 in many fonts.
java.time
These classes are now outmoded by the java.time framework built into Java 8 and later. The new classes are more sensible and easier to use.
Time Zone
A time zone is more than an offset-from-UTC. A time zone is an offset plus a set of past, present, and future rules for handling anomalies such as Daylight Saving Time. Use a proper time zone such as Europe/Berlin. Avoid using or even thinking about the 3-4 letter codes such as CET & CEST; they are neither standardized nor unique.
Example code
First we get an Instant, a moment on the timeline in UTC, from the count-from-epoch.
long milliSecondsFromEpochInUtc = 1445945400000L;
Instant instant = Instant.ofEpochMilli ( milliSecondsFromEpochInUtc );
Then we assign the desired time zone to get a ZonedDateTime.
ZoneId zoneId = ZoneId.of ( "Europe/Berlin" );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , zoneId );
For output, a formatter by default uses the ZonedDateTime object’s assigned time zone.
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime ( FormatStyle.MEDIUM ).withLocale ( Locale.GERMANY );
String output1 = zdt.format ( formatter );
Optionally a formatter may apply a different time zone if specified.
String output2 = zdt.format ( formatter.withZone ( ZoneId.of ( "America/Montreal" ) ) );
Dump to console.
System.out.println ( "instant (UTC): " + instant );
System.out.println ( "zdt: " + zdt );
System.out.println ( "Berlin time zone: " + output1 );
System.out.println ( "Montréal time zone: " + output2 );
When run. Note that all of these represent the same moment on the timeline. Their presentation varies but they all mean the same simultaneous moment.
instant (UTC): 2015-10-27T11:30:00Z
zdt: 2015-10-27T12:30+01:00[Europe/Berlin]
Berlin time zone: 27.10.2015 12:30:00
Montréal time zone: 27.10.2015 07:30:00

trying to fix a dereferencing error in java

I have a problem where i'm trying to find the date and time for a specific long value from the "new beginning of the universe", aka jan 1 1970.
I get a "cannot be dereferenced" error when i try to pass my new value to the toString thing.
What i don't get, is that this works for getting a time in millis and displaying it a more readable date/time format, so why not after i do a bunch of math with it?
import java.util.*;
public class Date {
public static void main(String[] args) {
Date mydate1 = new Date(10000);
System.out.println("The date and time of " +
mydate1.elapse + " from the Unix epoch is " + mydate1.getMyTime());
Date mydate2 = new Date(100000);
System.out.println("The date and time of " +
mydate2.elapse + " from the Unix epoch is " + mydate2.getMyTime());
Date mydate3 = new Date(1000000);
System.out.println("The date and time of " +
mydate3.elapse + " from the Unix epoch is " + mydate3.getMyTime());
Date mydate4 = new Date(10000000);
System.out.println("The date and time of " +
mydate4.elapse + " from the Unix epoch is " + mydate4.getMyTime());
Date mydate5 = new Date(100000000);
System.out.println("The date and time of " +
mydate5.elapse + " from the Unix epoch is " + mydate5.getMyTime());
Date mydate6 = new Date(1000000000);
System.out.println("The date and time of " +
mydate6.elapse + " from the Unix epoch is " + mydate6.getMyTime());
/*Date date7 = new Date(10000000000);
System.out.println("The date and time of " +
date7.elapse + " from the Unix epoch is " + date7.getTime());
Date date8 = new Date(100000000000);
System.out.println("The date and time of " +
date8.elapse + " from the Unix epoch is " + date8.getTime());*/
}
long elapse;
Date() {
elapse = 1;
}
Date(long elapseTime) {
elapse = elapseTime;
}
long getMyTime() {
//java.util.Date date = new.java.util.Date();
long currentMillis = System.currentTimeMillis();
long date = currentMillis + elapse - currentMillis;
System.out.println(date.toString());
You can't call toString() on a long (primitive type) -
// System.out.println(date.toString());
System.out.println(date); // <-- this would work.
System.out.println(String.valueOf(date)); // <-- this would be assignable to a
// String, but it prints the
// same value as the first example.
In
long date = currentMillis + elapse - currentMillis;
The variable date is a primitive (long) and not a object. toString is a method all java classes inherit from java.lang.Object and so will be available in all objects (that are instance of classes). long is just a primitive, primitives do not have methods, they do not inherit from Object either.
So all you need is
System.out.println(date);
The issue is in : System.out.println(date.toString())
date is of primitive type long (its not an object of wrapper class Long). Hence the method toString() is not available for 'date'. rather you can simple use :
System.out.println(date);
If you want to print the formatted Date use the following :
Dste d = new Date(date);
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
System.out.println(sdf.format(d));

Joda DateTime to Timestamp conversion

I am trying to change the value of Timestamp by DateTimeZone in Joda :
DateTime dt = new DateTime(rs.getTimestamp("anytimestampcolumn"),
DateTimeZone.forID("anytimezone"));
Timestamp ts = new Timestamp(dt.getMillis());
For DateTime, value is : 2013-04-13T22:56:27.000+03:00
For TimeStamp, value is : 2013-04-13 22:56:27.0
Timestamp is coming without timezone difference.
How can I get the correct Timestamp with TimeZone ?
For example I want to get "2013-05-13 01:56:27.0".
Edit : using MySQL, column type is TIMESTAMP of course, rs is ResultSet.
It is a common misconception that time (a measurable 4th dimension) is different over the world. Timestamp as a moment in time is unique. Date however is influenced how we "see" time but actually it is "time of day".
An example: two people look at the clock at the same moment. The timestamp is the same, right?
But one of them is in London and sees 12:00 noon (GMT, timezone offset is 0), and the other is in Belgrade and sees 14:00 (CET, Central Europe, daylight saving now, offset is +2).
Their perception is different but the moment is the same.
You can find more details in this answer.
UPDATE
OK, it's not a duplicate of this question but it is pointless since you are confusing the terms "Timestamp = moment in time (objective)" and "Date[Time] = time of day (subjective)".
Let's look at your original question code broken down like this:
// Get the "original" value from database.
Timestamp momentFromDB = rs.getTimestamp("anytimestampcolumn");
// Turn it into a Joda DateTime with time zone.
DateTime dt = new DateTime(momentFromDB, DateTimeZone.forID("anytimezone"));
// And then turn it back into a timestamp but "with time zone".
Timestamp ts = new Timestamp(dt.getMillis());
I haven't run this code but I am certain it will print true and the same number of milliseconds each time:
System.out.println("momentFromDB == dt : " + (momentFromDB.getTime() == dt.getTimeInMillis());
System.out.println("momentFromDB == ts : " + (momentFromDB.getTime() == ts.getTime()));
System.out.println("dt == ts : " + (dt.getTimeInMillis() == ts.getTime()));
System.out.println("momentFromDB [ms] : " + momentFromDB.getTime());
System.out.println("ts [ms] : " + ts.getTime());
System.out.println("dt [ms] : " + dt.getTimeInMillis());
But as you said yourself printing them out as strings will result in "different" time because DateTime applies the time zone. That's why "time" is stored and transferred as Timestamp objects (which basically wraps a long) and displayed or entered as Date[Time].
In your own answer you are artificially adding an offset and creating a "wrong" time.
If you use that timestamp to create another DateTime and print it out it will be offset twice.
// Turn it back into a Joda DateTime with time zone.
DateTime dt = new DateTime(ts, DateTimeZone.forID("anytimezone"));
P.S. If you have the time go through the very complex Joda Time source code to see how it holds the time (millis) and how it prints it.
JUnit Test as proof
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import org.junit.Before;
import org.junit.Test;
public class WorldTimeTest {
private static final int MILLIS_IN_HOUR = 1000 * 60 * 60;
private static final String ISO_FORMAT_NO_TZ = "yyyy-MM-dd'T'HH:mm:ss.SSS";
private static final String ISO_FORMAT_WITH_TZ = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
private TimeZone londonTimeZone;
private TimeZone newYorkTimeZone;
private TimeZone sydneyTimeZone;
private long nowInMillis;
private Date now;
public static SimpleDateFormat createDateFormat(String pattern, TimeZone timeZone) throws Exception {
SimpleDateFormat result = new SimpleDateFormat(pattern);
// Must explicitly set the time zone with "setCalendar()".
result.setCalendar(Calendar.getInstance(timeZone));
return result;
}
public static SimpleDateFormat createDateFormat(String pattern) throws Exception {
return createDateFormat(pattern, TimeZone.getDefault());
}
public static SimpleDateFormat createDateFormat() throws Exception {
return createDateFormat(ISO_FORMAT_WITH_TZ, TimeZone.getDefault());
}
public void printSystemInfo() throws Exception {
final String[] propertyNames = {
"java.runtime.name", "java.runtime.version", "java.vm.name", "java.vm.version",
"os.name", "os.version", "os.arch",
"user.language", "user.country", "user.script", "user.variant",
"user.language.format", "user.country.format", "user.script.format",
"user.timezone" };
System.out.println();
System.out.println("System Information:");
for (String name : propertyNames) {
if (name == null || name.length() == 0) {
continue;
}
String value = System.getProperty(name);
if (value != null && value.length() > 0) {
System.out.println(" " + name + " = " + value);
}
}
final TimeZone defaultTZ = TimeZone.getDefault();
final int defaultOffset = defaultTZ.getOffset(nowInMillis) / MILLIS_IN_HOUR;
final int userOffset = TimeZone.getTimeZone(System
.getProperty("user.timezone")).getOffset(nowInMillis) / MILLIS_IN_HOUR;
final Locale defaultLocale = Locale.getDefault();
System.out.println(" default.timezone-offset (hours) = " + userOffset);
System.out.println(" default.timezone = " + defaultTZ.getDisplayName());
System.out.println(" default.timezone.id = " + defaultTZ.getID());
System.out.println(" default.timezone-offset (hours) = " + defaultOffset);
System.out.println(" default.locale = "
+ defaultLocale.getLanguage() + "_" + defaultLocale.getCountry()
+ " (" + defaultLocale.getDisplayLanguage()
+ "," + defaultLocale.getDisplayCountry() + ")");
System.out.println(" now = " + nowInMillis + " [ms] or "
+ createDateFormat().format(now));
System.out.println();
}
#Before
public void setUp() throws Exception {
// Remember this moment.
now = new Date();
nowInMillis = now.getTime(); // == System.currentTimeMillis();
// Print out some system information.
printSystemInfo();
// "Europe/London" time zone is DST aware, we'll use fixed offset.
londonTimeZone = TimeZone.getTimeZone("GMT");
// The same applies to "America/New York" time zone ...
newYorkTimeZone = TimeZone.getTimeZone("GMT-5");
// ... and for the "Australia/Sydney" time zone.
sydneyTimeZone = TimeZone.getTimeZone("GMT+10");
}
#Test
public void testDateFormatting() throws Exception {
int londonOffset = londonTimeZone.getOffset(nowInMillis) / MILLIS_IN_HOUR; // in hours
Calendar londonCalendar = Calendar.getInstance(londonTimeZone);
londonCalendar.setTime(now);
int newYorkOffset = newYorkTimeZone.getOffset(nowInMillis) / MILLIS_IN_HOUR;
Calendar newYorkCalendar = Calendar.getInstance(newYorkTimeZone);
newYorkCalendar.setTime(now);
int sydneyOffset = sydneyTimeZone.getOffset(nowInMillis) / MILLIS_IN_HOUR;
Calendar sydneyCalendar = Calendar.getInstance(sydneyTimeZone);
sydneyCalendar.setTime(now);
// Check each time zone offset.
assertThat(londonOffset, equalTo(0));
assertThat(newYorkOffset, equalTo(-5));
assertThat(sydneyOffset, equalTo(10));
// Check that calendars are not equals (due to time zone difference).
assertThat(londonCalendar, not(equalTo(newYorkCalendar)));
assertThat(londonCalendar, not(equalTo(sydneyCalendar)));
// Check if they all point to the same moment in time, in milliseconds.
assertThat(londonCalendar.getTimeInMillis(), equalTo(nowInMillis));
assertThat(newYorkCalendar.getTimeInMillis(), equalTo(nowInMillis));
assertThat(sydneyCalendar.getTimeInMillis(), equalTo(nowInMillis));
// Check if they all point to the same moment in time, as Date.
assertThat(londonCalendar.getTime(), equalTo(now));
assertThat(newYorkCalendar.getTime(), equalTo(now));
assertThat(sydneyCalendar.getTime(), equalTo(now));
// Check if hours are all different (skip local time because
// this test could be executed in those exact time zones).
assertThat(newYorkCalendar.get(Calendar.HOUR_OF_DAY),
not(equalTo(londonCalendar.get(Calendar.HOUR_OF_DAY))));
assertThat(sydneyCalendar.get(Calendar.HOUR_OF_DAY),
not(equalTo(londonCalendar.get(Calendar.HOUR_OF_DAY))));
// Display London time in multiple forms.
SimpleDateFormat dfLondonNoTZ = createDateFormat(ISO_FORMAT_NO_TZ, londonTimeZone);
SimpleDateFormat dfLondonWithTZ = createDateFormat(ISO_FORMAT_WITH_TZ, londonTimeZone);
System.out.println("London (" + londonTimeZone.getDisplayName(false, TimeZone.SHORT)
+ ", " + londonOffset + "):");
System.out.println(" time (ISO format w/o TZ) = "
+ dfLondonNoTZ.format(londonCalendar.getTime()));
System.out.println(" time (ISO format w/ TZ) = "
+ dfLondonWithTZ.format(londonCalendar.getTime()));
System.out.println(" time (default format) = "
+ londonCalendar.getTime() + " / " + londonCalendar.toString());
// Using system default time zone.
System.out.println(" time (default TZ) = "
+ createDateFormat(ISO_FORMAT_NO_TZ).format(londonCalendar.getTime())
+ " / " + createDateFormat().format(londonCalendar.getTime()));
// Display New York time in multiple forms.
SimpleDateFormat dfNewYorkNoTZ = createDateFormat(ISO_FORMAT_NO_TZ, newYorkTimeZone);
SimpleDateFormat dfNewYorkWithTZ = createDateFormat(ISO_FORMAT_WITH_TZ, newYorkTimeZone);
System.out.println("New York (" + newYorkTimeZone.getDisplayName(false, TimeZone.SHORT)
+ ", " + newYorkOffset + "):");
System.out.println(" time (ISO format w/o TZ) = "
+ dfNewYorkNoTZ.format(newYorkCalendar.getTime()));
System.out.println(" time (ISO format w/ TZ) = "
+ dfNewYorkWithTZ.format(newYorkCalendar.getTime()));
System.out.println(" time (default format) = "
+ newYorkCalendar.getTime() + " / " + newYorkCalendar.toString());
// Using system default time zone.
System.out.println(" time (default TZ) = "
+ createDateFormat(ISO_FORMAT_NO_TZ).format(newYorkCalendar.getTime())
+ " / " + createDateFormat().format(newYorkCalendar.getTime()));
// Display Sydney time in multiple forms.
SimpleDateFormat dfSydneyNoTZ = createDateFormat(ISO_FORMAT_NO_TZ, sydneyTimeZone);
SimpleDateFormat dfSydneyWithTZ = createDateFormat(ISO_FORMAT_WITH_TZ, sydneyTimeZone);
System.out.println("Sydney (" + sydneyTimeZone.getDisplayName(false, TimeZone.SHORT)
+ ", " + sydneyOffset + "):");
System.out.println(" time (ISO format w/o TZ) = "
+ dfSydneyNoTZ.format(sydneyCalendar.getTime()));
System.out.println(" time (ISO format w/ TZ) = "
+ dfSydneyWithTZ.format(sydneyCalendar.getTime()));
System.out.println(" time (default format) = "
+ sydneyCalendar.getTime() + " / " + sydneyCalendar.toString());
// Using system default time zone.
System.out.println(" time (default TZ) = "
+ createDateFormat(ISO_FORMAT_NO_TZ).format(sydneyCalendar.getTime())
+ " / " + createDateFormat().format(sydneyCalendar.getTime()));
}
#Test
public void testDateParsing() throws Exception {
// Create date parsers that look for time zone information in a date-time string.
final SimpleDateFormat londonFormatTZ = createDateFormat(ISO_FORMAT_WITH_TZ, londonTimeZone);
final SimpleDateFormat newYorkFormatTZ = createDateFormat(ISO_FORMAT_WITH_TZ, newYorkTimeZone);
final SimpleDateFormat sydneyFormatTZ = createDateFormat(ISO_FORMAT_WITH_TZ, sydneyTimeZone);
// Create date parsers that ignore time zone information in a date-time string.
final SimpleDateFormat londonFormatLocal = createDateFormat(ISO_FORMAT_NO_TZ, londonTimeZone);
final SimpleDateFormat newYorkFormatLocal = createDateFormat(ISO_FORMAT_NO_TZ, newYorkTimeZone);
final SimpleDateFormat sydneyFormatLocal = createDateFormat(ISO_FORMAT_NO_TZ, sydneyTimeZone);
// We are looking for the moment this millenium started, the famous Y2K,
// when at midnight everyone welcomed the New Year 2000, i.e. 2000-01-01 00:00:00.
// Which of these is the right one?
// a) "2000-01-01T00:00:00.000-00:00"
// b) "2000-01-01T00:00:00.000-05:00"
// c) "2000-01-01T00:00:00.000+10:00"
// None of them? All of them?
// For those who guessed it - yes, it is a trick question because we didn't specify
// the "where" part, or what kind of time (local/global) we are looking for.
// The first (a) is the local Y2K moment in London, which is at the same time global.
// The second (b) is the local Y2K moment in New York, but London is already celebrating for 5 hours.
// The third (c) is the local Y2K moment in Sydney, and they started celebrating 15 hours before New York did.
// The point here is that each answer is correct because everyone thinks of that moment in terms of "celebration at midnight".
// The key word here is "midnight"! That moment is actually a "time of day" moment illustrating our perception of time based on the movement of our Sun.
// These are global Y2K moments, i.e. the same moment all over the world, UTC/GMT midnight.
final String MIDNIGHT_GLOBAL = "2000-01-01T00:00:00.000-00:00";
final Date milleniumInLondon = londonFormatTZ.parse(MIDNIGHT_GLOBAL);
final Date milleniumInNewYork = newYorkFormatTZ.parse(MIDNIGHT_GLOBAL);
final Date milleniumInSydney = sydneyFormatTZ.parse(MIDNIGHT_GLOBAL);
// Check if they all point to the same moment in time.
// And that parser ignores its own configured time zone and uses the information from the date-time string.
assertThat(milleniumInNewYork, equalTo(milleniumInLondon));
assertThat(milleniumInSydney, equalTo(milleniumInLondon));
// These are all local Y2K moments, a.k.a. midnight at each location on Earth, with time zone information.
final String MIDNIGHT_LONDON = "2000-01-01T00:00:00.000-00:00";
final String MIDNIGHT_NEW_YORK = "2000-01-01T00:00:00.000-05:00";
final String MIDNIGHT_SYDNEY = "2000-01-01T00:00:00.000+10:00";
final Date midnightInLondonTZ = londonFormatLocal.parse(MIDNIGHT_LONDON);
final Date midnightInNewYorkTZ = newYorkFormatLocal.parse(MIDNIGHT_NEW_YORK);
final Date midnightInSydneyTZ = sydneyFormatLocal.parse(MIDNIGHT_SYDNEY);
// Check if they all point to the same moment in time.
assertThat(midnightInNewYorkTZ, not(equalTo(midnightInLondonTZ)));
assertThat(midnightInSydneyTZ, not(equalTo(midnightInLondonTZ)));
// Check if the time zone offset is correct.
assertThat(midnightInLondonTZ.getTime() - midnightInNewYorkTZ.getTime(),
equalTo((long) newYorkTimeZone.getOffset(milleniumInLondon.getTime())));
assertThat(midnightInLondonTZ.getTime() - midnightInSydneyTZ.getTime(),
equalTo((long) sydneyTimeZone.getOffset(milleniumInLondon.getTime())));
// These are also local Y2K moments, just withouth the time zone information.
final String MIDNIGHT_ANYWHERE = "2000-01-01T00:00:00.000";
final Date midnightInLondon = londonFormatLocal.parse(MIDNIGHT_ANYWHERE);
final Date midnightInNewYork = newYorkFormatLocal.parse(MIDNIGHT_ANYWHERE);
final Date midnightInSydney = sydneyFormatLocal.parse(MIDNIGHT_ANYWHERE);
// Check if these are the same as the local moments with time zone information.
assertThat(midnightInLondon, equalTo(midnightInLondonTZ));
assertThat(midnightInNewYork, equalTo(midnightInNewYorkTZ));
assertThat(midnightInSydney, equalTo(midnightInSydneyTZ));
// Check if they all point to the same moment in time.
assertThat(midnightInNewYork, not(equalTo(midnightInLondon)));
assertThat(midnightInSydney, not(equalTo(midnightInLondon)));
// Check if the time zone offset is correct.
assertThat(midnightInLondon.getTime() - midnightInNewYork.getTime(),
equalTo((long) newYorkTimeZone.getOffset(milleniumInLondon.getTime())));
assertThat(midnightInLondon.getTime() - midnightInSydney.getTime(),
equalTo((long) sydneyTimeZone.getOffset(milleniumInLondon.getTime())));
// Final check - if Y2K moment is in London ..
final String Y2K_LONDON = "2000-01-01T00:00:00.000Z";
// .. New York local time would be still 5 hours in 1999 ..
final String Y2K_NEW_YORK = "1999-12-31T19:00:00.000-05:00";
// .. and Sydney local time would be 10 hours in 2000.
final String Y2K_SYDNEY = "2000-01-01T10:00:00.000+10:00";
final String londonTime = londonFormatTZ.format(milleniumInLondon);
final String newYorkTime = newYorkFormatTZ.format(milleniumInLondon);
final String sydneyTime = sydneyFormatTZ.format(milleniumInLondon);
// WHat do you think, will the test pass?
assertThat(londonTime, equalTo(Y2K_LONDON));
assertThat(newYorkTime, equalTo(Y2K_NEW_YORK));
assertThat(sydneyTime, equalTo(Y2K_SYDNEY));
}
}
Actually this is not a duplicate question. And this how i solve my problem after several times :
int offset = DateTimeZone.forID("anytimezone").getOffset(new DateTime());
This is the way to get offset from desired timezone.
Let's return to our code, we were getting timestamp from a result set of query, and using it with timezone to create our datetime.
DateTime dt = new DateTime(rs.getTimestamp("anytimestampcolumn"),
DateTimeZone.forID("anytimezone"));
Now we will add our offset to the datetime, and get the timestamp from it.
dt = dt.plusMillis(offset);
Timestamp ts = new Timestamp(dt.getMillis());
May be this is not the actual way to get it, but it solves my case. I hope it helps anyone who is stuck here.
//This Works just fine
DateTime dt = new DateTime();
Log.d("ts",String.valueOf(dt.now()));
dt=dt.plusYears(3);
dt=dt.minusDays(7);
Log.d("JODA DateTime",String.valueOf(dt));
Timestamp ts= new Timestamp(dt.getMillis());
Log.d("Coverted to java.sql.Timestamp",String.valueOf(ts));
I've solved this problem in this way.
String dateUTC = rs.getString("date"); //UTC
DateTime date;
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS").withZoneUTC();
date = dateTimeFormatter.parseDateTime(dateUTC);
In this way you ignore the server TimeZone forcing your chosen TimeZone.

Java date parsing: distinguish between 28/10/2012 2:00 CET and 28/10/2012 2:00 CEST

I have a list of dates as strings, namely:
28/10/2012 00:00
28/10/2012 01:00
28/10/2012 02:00
28/10/2012 02:00
28/10/2012 03:00
(the same hour twice is because of DST)
And I need to make sure that between each of the dates there's exactly one hour.
The problem here is that the first 28/10/2012 02:00 is CEST, while the second one is CET. Distinguishing them is the easy part because the first one is CEST while the second is CET. The hard part is how can I specify to SimpleDateFormat (or another date parsing class) that the string represents a CEST/CET time so I can get the correct Date object?
Thanks in advance!
consider the following example
i think it has your answer convert String to Date with SimpleDateFormat considering CET CEST
public class DatesAndTimesStackOverflow {
final static SimpleDateFormat sdf;
final static TimeZone tz;
static {
tz = TimeZone.getTimeZone( "Europe/Paris" );
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zzz");
sdf.setTimeZone(tz);
}
public static void main(String[] args) {
// october clock change should be the following:
outputDateInfo("2012-10-28 02:00:00 CEST");
outputDateInfo("2012-10-28 02:30:00 CEST");
outputDateInfo("2012-10-28 02:00:00 CET");
outputDateInfo("2012-10-28 02:30:00 CET");
outputDateInfo("2012-10-28 03:00:00 CET");
outputDateInfo("2012-10-28 03:30:00 CET");
outputDateInfo("2012-10-28 04:00:00 CET");
}
private static void outputDateInfo(String theDate) {
try {
output("------------------------------------------------------------------------------");
Date d = sdf.parse(theDate);
Calendar c = GregorianCalendar.getInstance(tz);
c.setTimeInMillis(d.getTime());
TimeZone tzCal = c.getTimeZone();
output("String: " + theDate);
output("");
output("Date: " + d); // toString uses current system TimeZone
output("Date Millis: " + d.getTime());
output("Cal Millis: " + c.getTimeInMillis());
output("Cal To Date Millis: " + c.getTime().getTime());
output("Cal TimeZone Name: " + tzCal.getDisplayName());
output("Cal TimeZone ID: " + tzCal.getID());
output("Cal TimeZone DST Name: " + tzCal.getDisplayName(true, TimeZone.SHORT));
output("Cal TimeZone Standard Name: " + tzCal.getDisplayName(false, TimeZone.SHORT));
output("In DayLight: " + tzCal.inDaylightTime(d));
output("");
output("Day Of Month: " + c.get(Calendar.DAY_OF_MONTH));
output("Month Of Year: " + c.get(Calendar.MONTH));
output("Year: " + c.get(Calendar.YEAR));
output("Hour Of Day: " + c.get(Calendar.HOUR_OF_DAY));
output("Minute: " + c.get(Calendar.MINUTE));
output("Second: " + c.get(Calendar.SECOND));
// check to see if this converts back to correct string
String reformat = sdf.format(c.getTime());
if( reformat.equals(theDate) ) {
output("ReConvert: " + reformat + " OK");
} else {
output("ReConvert: " + reformat + " <-------- Error. The converted date is different");
}
} catch (ParseException ex) {
output("Cannot parse this date");
}
}
private static void output(String message) {
System.out.println(message);
}
}

Categories

Resources