yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z' format - java

I am trying to convert GMT to IST.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS");
Date c= sdf.parse("2017-03-31T10:38:14.4723017Z");
Date date = new Date();
DateFormat istFormat = new SimpleDateFormat();
DateFormat gmtFormat = new SimpleDateFormat();
TimeZone gmtTime = TimeZone.getTimeZone("GMT");
TimeZone istTime = TimeZone.getTimeZone("IST");
istFormat.setTimeZone(gmtTime);
gmtFormat.setTimeZone(istTime);
System.out.println("GMT Time: " + istFormat.format(c));
System.out.println("IST Time: " + gmtFormat.format(c));
My output is
GMT Time: 31/3/17 6:26 AM
IST Time: 31/3/17 11:56 AM
But my actual output should be
GMT Time: 31/3/17 5:08 AM
IST Time: 31/3/17 10:38 AM
What is wrong with my code?

Milliseconds (SSS) can only be three digits. On more than that, the date rolls over - e.g. 10:38:14.1000 becomes 10:38:15.000. Add a couple of million milliseconds... and you get the behaviour that you're seeing now.
Try this.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
Date c = sdf.parse("2017-03-31T10:38:14.472Z");
System.out.println(c);
DateFormat istFormat = new SimpleDateFormat();
DateFormat gmtFormat = new SimpleDateFormat();
TimeZone gmtTime = TimeZone.getTimeZone("GMT");
TimeZone istTime = TimeZone.getTimeZone("IST");
istFormat.setTimeZone(gmtTime);
gmtFormat.setTimeZone(istTime);
System.out.println("GMT Time: " + istFormat.format(c));
System.out.println("IST Time: " + gmtFormat.format(c));

Have you tried changing the format to "yyyy-MM-dd'T'HH:mm:ss.sssssssZ"?
Also, when you type Z in your Date object, you should write the time zone designator, for example, "2017-03-31T10:38:14.4723017+01:00".

Try use this format "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZ"

Related

Converting date from UTC to CET [duplicate]

This question already has answers here:
Convert Date/Time for given Timezone - java
(16 answers)
Closed 6 years ago.
I would like to convert a date given in the UTC format to a date in the CET format.
The problem is that I need to add or subtract hours accordingly.
Example:
Date = "2015-07-31 01:14:05"
I would like to convert it to German date (adding two hours):
2015-07-31 03:14:05"
My code:
private static Long convertDateFromUtcToCet(String publicationDate) {
//"2015-07-31 01:14:05"
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
//SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd");
Date date = null;
try {
date = simpleDateFormat.parse(publicationDate);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.setTime(date);
Date givenDate = calendar.getTime();
System.out.println("Original UTC date is: " + givenDate.toString());
TimeZone timeZone = TimeZone.getTimeZone("CET");
calendar.setTimeZone(timeZone);
Date currentDate = calendar.getTime();
System.out.println("CET date is: " + currentDate.toString());
long milliseconds = calendar.getTimeInMillis();
return milliseconds;
}
This prints:
Original UTC date is: Sat Jan 31 01:14:05 IST 2015
CET date is: Sat Jan 31 01:14:05 IST 2015
First of all, your pattern string is wrong. It's yyyy-MM-dd, not yyyy-mm-dd.
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
To parse with a given time zone, set it with:
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Try using:
long ts = System.currentTimeMillis();
Date localTime = new Date(ts);
String format = "yyyy-mm-dd hh:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(format);
// Convert Local Time to UTC (Works Fine)
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date gmtTime = new Date(sdf.format(localTime));
System.out.println("Local:" + localTime.toString() + "," + localTime.getTime() + " --> UTC time:"
+ gmtTime.toString() + "," + gmtTime.getTime());
// Convert UTC to Local Time
Date fromGmt = new Date(gmtTime.getTime() + TimeZone.getDefault().getOffset(localTime.getTime()));
System.out.println("UTC time:" + gmtTime.toString() + "," + gmtTime.getTime() + " --> Local:"
+ fromGmt.toString() + "-" + fromGmt.getTime());

GMT To Local Covert In Wrong Way ( False Value )

i have the following code that converts GMT time to local time, I took it from an answer here on StackOverflow, the problem is that this code return a false value of GMT time .
My GMT Time is : +3, but the code is using +2, it takes the GMT time from my device i guess, and my device's time is +3 GMT .
Here's the code :
String inputText = "12:00";
SimpleDateFormat inputFormat = new SimpleDateFormat
("kk:mm", Locale.US);
inputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat outputFormat =
new SimpleDateFormat("kk:mm");
// Adjust locale and zone appropriately
Date date = null;
try {
date = inputFormat.parse(inputText);
} catch (ParseException e) {
e.printStackTrace();
}
String outputText = outputFormat.format(date);
Log.i("Time","Time Is: " + outputText);
The log returns : 14:00
This is related to the date on which you are doing the conversion.
You are only specifying the hours and minutes, so the calculation is being done on January 1 1970. On that date, presumably, the GMT offset in your timezone is just 2 hours.
Specify the date too.
SimpleDateFormat inputFormat =
new SimpleDateFormat("kk:mm", Locale.US);
inputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat outputFormat =
new SimpleDateFormat("yyyy/MM/dd kk:mm", Locale.US);
outputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = inputFormat.parse("12:00");
System.out.println("Time Is: " + outputFormat.format(date));
Ideone demo
Output:
Time Is: 1970/01/01 12:00
Additional code to show Daylight Savings Time / Summer Time impact:
SimpleDateFormat gmtFormat = new SimpleDateFormat("yyyy/MM/dd kk:mm", Locale.US);
gmtFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat finlandFormat = new SimpleDateFormat("yyyy/MM/dd kk:mm zzz", Locale.US);
finlandFormat.setTimeZone(TimeZone.getTimeZone("Europe/Helsinki"));
SimpleDateFormat plus3Format = new SimpleDateFormat("yyyy/MM/dd kk:mm zzz", Locale.US);
plus3Format.setTimeZone(TimeZone.getTimeZone("GMT+3"));
Date date = gmtFormat.parse("1970/01/01 12:00");
System.out.println("Time Is: " + gmtFormat.format(date));
System.out.println("Time Is: " + finlandFormat.format(date));
System.out.println("Time Is: " + plus3Format.format(date));
date = gmtFormat.parse("2016/04/22 12:00");
System.out.println("Time Is: " + gmtFormat.format(date));
System.out.println("Time Is: " + finlandFormat.format(date));
System.out.println("Time Is: " + plus3Format.format(date));
Output:
Time Is: 1970/01/01 12:00
Time Is: 1970/01/01 14:00 EET <-- Eastern European Time
Time Is: 1970/01/01 15:00 GMT+03:00
Time Is: 2016/04/22 12:00
Time Is: 2016/04/22 15:00 EEST <-- Eastern European Summer Time
Time Is: 2016/04/22 15:00 GMT+03:00

Simpledateformat parse subtracts instead of adding

I'm trying to change the time that I get (in CEST/CET) to GMT to store it in my database. BUT when I parse the date in CEST to GMT, instead of subtracting 2, it adds 2 hours!
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()); //My locale is CEST
Date dateOfBooking = formatter.parse(bookedDate + " " + bookedDateTime); //Here the time is 10:09
formatter.setTimeZone(TimeZone.getTimeZone("GMT")); // Timezone I need to store the date in
dateOfBooking = formatter.parse(bookedDate + " " + bookedDateTime); // Here the time is 12:09
DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
bookedDateTime = timeFormat.format(dateOfBooking);
Can anybody explain why? I've tried setting my local timezone to different ones and it always work the other way, subtracting instead of adding and viceversa.
You are parsing the date again as GMT. (which, when printed as CEST, or your locale timezone, will add + 2 hours)
What you actually want is to print out the already parsed date as GMT:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()); //My locale is CEST
Date dateOfBooking = formatter.parse(bookedDate + " " + bookedDateTime); //Here the time is 10:09
DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
timeFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
bookedDateTime = timeFormat.format(dateOfBooking);
System.out.println(bookedDateTime);
Basicly you have to set the GMT zone in your timeFormat that you use to create the time string, not the formatter that you use for parsing

How do I convert date/time from one timezone to another? [duplicate]

i have written this code to convert the current system date and time to some other timezone. I am not getting any error but i am not getting my output as expected. Like if i execute my program at a particular time.. My output is ::
The current time in India is :: Fri Feb 24 16:09:23 IST 2012
The date and time in :: Central Standard Time is :: Sat Feb 25 03:39:23 IST 2012
And the actual Time according to CST time zone is ::
Friday, 24 February 4:39:16 a.m(GMT - 6:00)
So there's some time gap. and i don't know why this is happening. Any help will be appreciated.. The code is ::
package MyPackage;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class Temp2 {
public static void main(String[] args) {
try {
Calendar currentdate = Calendar.getInstance();
String strdate = null;
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
strdate = formatter.format(currentdate.getTime());
TimeZone obj = TimeZone.getTimeZone("CST");
formatter.setTimeZone(obj);
//System.out.println(strdate);
//System.out.println(formatter.parse(strdate));
Date theResult = formatter.parse(strdate);
System.out.println("The current time in India is :: " +currentdate.getTime());
System.out.println("The date and time in :: "+ obj.getDisplayName() + "is ::" + theResult);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
It's over the web. Could have googled. Anyways, here is a version for you (shamelessly picked and modified from here):
Calendar calendar = Calendar.getInstance();
TimeZone fromTimeZone = calendar.getTimeZone();
TimeZone toTimeZone = TimeZone.getTimeZone("CST");
calendar.setTimeZone(fromTimeZone);
calendar.add(Calendar.MILLISECOND, fromTimeZone.getRawOffset() * -1);
if (fromTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, calendar.getTimeZone().getDSTSavings() * -1);
}
calendar.add(Calendar.MILLISECOND, toTimeZone.getRawOffset());
if (toTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, toTimeZone.getDSTSavings());
}
System.out.println(calendar.getTime());
Your mistake is to call parse instead of format.
You call parse to parse a Date from a String, but in your case you've got a Date and need to format it using the correct Timezone.
Replace your code with
Calendar currentdate = Calendar.getInstance();
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
TimeZone obj = TimeZone.getTimeZone("CST");
formatter.setTimeZone(obj);
System.out.println("Local:: " +currentdate.getTime());
System.out.println("CST:: "+ formatter.format(currentdate.getTime()));
and I hope you'll get the output you are expecting.
SimpleDateFormat#setTimezone() is the answer. One formatter with ETC timezone you use for parsing, another with UTC for producing output string:
DateFormat dfNy = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ROOT);
dfNy.setTimeZone(TimeZone.getTimeZone("EST"));
DateFormat dfUtc = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ROOT);
dfUtc.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
return dfUtc.format(dfNy.parse(input));
} catch (ParseException e) {
return null; // invalid input
}
Handling dates in Java in my daily work is a non-trivial task. I suggest you to use Joda-Time that simplify our coding days and you don't have to "re-invent the wheel".
You can use two SimpleDateFormat, one for parse the date string with EST timezone, one for print the date with UTC timezone
String format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat estFormatter = new SimpleDateFormat(format);
estFormatter.setTimeZone(TimeZone.getTimeZone("EST"));
Date date = estFormatter.parse("2015-11-01 01:00:00");
SimpleDateFormat utcFormatter = new SimpleDateFormat(format);
utcFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(utcFormatter.format(date));
You can just use "CST6CDT"
because in some countries they follow CDT in summer and CST in winter
public static String getDateInCST() {
Calendar calendar = Calendar.getInstance();
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
formatter.setTimeZone(TimeZone.getTimeZone( "CST6CDT"));
String strdate = formatter.format(calendar.getTime());
TimeZone.getAvailableIDs();
return strdate;
}
Problem is when you print date obj it call toString method and it will print in your machines default time zone. Try this code and see difference.
Calendar currentdate = Calendar.getInstance();
String strdate = null;
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ssz");
strdate = formatter.format(currentdate.getTime());
System.out.println("strdate=>" + strdate);
TimeZone obj = TimeZone.getTimeZone("CST");
formatter.setTimeZone(obj);
strdate = formatter.format(currentdate.getTime());
Date theResult = formatter.parse(strdate);
System.out.println("The current time in India is :: " +currentdate.getTime());
System.out.println("The date and time in :: " + obj.getDisplayName() + "is ::" + theResult);
System.out.println("The date and time in :: " + obj.getDisplayName() + "is ::" + strdate);
First message, don’t handle your date and time as strings in your code. Just as you don’t handle numbers and Boolean values as strings (I hope). Use proper date-time objects.
java.time
Sometimes we get date and time as string input. It may be from a text file, from the user or from data exchange with another system, for example. In those cases parse into a proper date-time object first thing. Second message, use java.time, the modern Java date and time API, for your date and time work.
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
String input = "2015-11-01 01:00:00";
ZonedDateTime nyTime = LocalDateTime.parse(input, formatter)
.atZone(ZoneId.of("America/New_York"));
System.out.println("Time in New York: " + nyTime);
Output from this snippet is:
Time in New York: 2015-11-01T01:00-04:00[America/New_York]
To convert to GMT:
OffsetDateTime gmtTime = nyTime.toOffsetDateTime()
.withOffsetSameInstant(ZoneOffset.UTC);
System.out.println("GMT Time: " + gmtTime);
GMT Time: 2015-11-01T05:00Z
If you need to give string output, format using a date-time formatter. Here’s an example of formatting for an American audience:
DateTimeFormatter userFormatter
= DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
.withLocale(Locale.US);
String formattedDateTime = gmtTime.format(userFormatter);
System.out.println("GMT Time formatted for user: " + formattedDateTime);
GMT Time formatted for user: Nov 1, 2015, 5:00:00 AM
You additionally asked:
Between the two results below, which one should you take?
I understand that you ask because both are valid answers. On November 1, 2015 summer time (DST) ended at 2 AM. That is, after 01:59:59 came 01:00:00 a second time. So when we have got 2015-11-01 01:00:00 as input, it is ambiguous. It could be in Eastern Daylight Time, equal to 05:00 GMT, or it could be in Eastern Standard Time, one hour later, hence equal to 06:00 GMT. There is no way that I can tell you which of them is correct in your case. You may control which result you get using withEarlierOffsetAtOverlap() or withLaterOffsetAtOverlap(). Above we got the DST interpretation. So to get the standard time interpretation:
nyTime = nyTime.withLaterOffsetAtOverlap();
System.out.println("Alternate time in New York: " + nyTime);
Alternate time in New York: 2015-11-01T01:00-05:00[America/New_York]
We notice that the hour of day is still 01:00, but the offset is now -05:00 instead of -04:00. This also gives us a different GMT time:
GMT Time: 2015-11-01T06:00Z
GMT Time formatted for user: Nov 1, 2015, 6:00:00 AM
Avoid SimpleDateFormat and friends
While the other answers are generally correct, the classes DateFormat, SimpleDateFormat, Date and Calendar used there are poorly designed and long outdated. The first two are particularly troublesome. I recommend you avoid all of them. I frankly find the modern API so much nicer to work with.
Link
Oracle tutorial: Date Time explaining how to use java.time.
Please refer to below mentioned code.
DateFormat utcConverter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
utcConverter.setTimeZone(TimeZone.getTimeZone("GMT"));
String sampleDateTime = "2015-11-01 01:00:00";
DateFormat nyConverter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
nyConverter.setTimeZone(TimeZone.getTimeZone("EST"));
Calendar nyCal = Calendar.getInstance();
nyCal.setTime(nyConverter.parse(sampleDateTime));
System.out.println("NY TIME :" +nyConverter.format(nyCal.getTime()));
System.out.println("GMT TIME :" +utcConverter.format(nyCal.getTime()));
2020 Answer Here
If you want the new java.time.* feature but still want to mess with java.util.Date:
public static Date convertBetweenTwoTimeZone(Date date, String fromTimeZone, String toTimeZone) {
ZoneId fromTimeZoneId = ZoneId.of(fromTimeZone);
ZoneId toTimeZoneId = ZoneId.of(toTimeZone);
ZonedDateTime fromZonedDateTime =
ZonedDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()).withZoneSameLocal(fromTimeZoneId);
ZonedDateTime toZonedDateTime = fromZonedDateTime
.withZoneSameInstant(toTimeZoneId)
.withZoneSameLocal(ZoneId.systemDefault())
;
return Date.from(toZonedDateTime.toInstant());
}
for java.sql.Timestamp
public static Timestamp convertBetweenTwoTimeZone(Timestamp timestamp, String fromTimeZone, String toTimeZone) {
ZoneId fromTimeZoneId = ZoneId.of(fromTimeZone);
ZoneId toTimeZoneId = ZoneId.of(toTimeZone);
LocalDateTime localDateTimeBeforeDST = timestamp.toLocalDateTime();
ZonedDateTime fromZonedDateTime = ZonedDateTime.of(localDateTimeBeforeDST, fromTimeZoneId);
ZonedDateTime toZonedDateTime = fromZonedDateTime.withZoneSameInstant(toTimeZoneId);
return Timestamp.valueOf(toZonedDateTime.toLocalDateTime());
}
For google calendar API
private String getFormatedDate(Date date)
{
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss+05:30");
df.setTimeZone(TimeZone.getTimeZone("GMT+05:30"));
return df.format(date);
}

Date and time conversion to some other Timezone in java

i have written this code to convert the current system date and time to some other timezone. I am not getting any error but i am not getting my output as expected. Like if i execute my program at a particular time.. My output is ::
The current time in India is :: Fri Feb 24 16:09:23 IST 2012
The date and time in :: Central Standard Time is :: Sat Feb 25 03:39:23 IST 2012
And the actual Time according to CST time zone is ::
Friday, 24 February 4:39:16 a.m(GMT - 6:00)
So there's some time gap. and i don't know why this is happening. Any help will be appreciated.. The code is ::
package MyPackage;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class Temp2 {
public static void main(String[] args) {
try {
Calendar currentdate = Calendar.getInstance();
String strdate = null;
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
strdate = formatter.format(currentdate.getTime());
TimeZone obj = TimeZone.getTimeZone("CST");
formatter.setTimeZone(obj);
//System.out.println(strdate);
//System.out.println(formatter.parse(strdate));
Date theResult = formatter.parse(strdate);
System.out.println("The current time in India is :: " +currentdate.getTime());
System.out.println("The date and time in :: "+ obj.getDisplayName() + "is ::" + theResult);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
It's over the web. Could have googled. Anyways, here is a version for you (shamelessly picked and modified from here):
Calendar calendar = Calendar.getInstance();
TimeZone fromTimeZone = calendar.getTimeZone();
TimeZone toTimeZone = TimeZone.getTimeZone("CST");
calendar.setTimeZone(fromTimeZone);
calendar.add(Calendar.MILLISECOND, fromTimeZone.getRawOffset() * -1);
if (fromTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, calendar.getTimeZone().getDSTSavings() * -1);
}
calendar.add(Calendar.MILLISECOND, toTimeZone.getRawOffset());
if (toTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, toTimeZone.getDSTSavings());
}
System.out.println(calendar.getTime());
Your mistake is to call parse instead of format.
You call parse to parse a Date from a String, but in your case you've got a Date and need to format it using the correct Timezone.
Replace your code with
Calendar currentdate = Calendar.getInstance();
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
TimeZone obj = TimeZone.getTimeZone("CST");
formatter.setTimeZone(obj);
System.out.println("Local:: " +currentdate.getTime());
System.out.println("CST:: "+ formatter.format(currentdate.getTime()));
and I hope you'll get the output you are expecting.
SimpleDateFormat#setTimezone() is the answer. One formatter with ETC timezone you use for parsing, another with UTC for producing output string:
DateFormat dfNy = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ROOT);
dfNy.setTimeZone(TimeZone.getTimeZone("EST"));
DateFormat dfUtc = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ROOT);
dfUtc.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
return dfUtc.format(dfNy.parse(input));
} catch (ParseException e) {
return null; // invalid input
}
Handling dates in Java in my daily work is a non-trivial task. I suggest you to use Joda-Time that simplify our coding days and you don't have to "re-invent the wheel".
You can use two SimpleDateFormat, one for parse the date string with EST timezone, one for print the date with UTC timezone
String format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat estFormatter = new SimpleDateFormat(format);
estFormatter.setTimeZone(TimeZone.getTimeZone("EST"));
Date date = estFormatter.parse("2015-11-01 01:00:00");
SimpleDateFormat utcFormatter = new SimpleDateFormat(format);
utcFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(utcFormatter.format(date));
You can just use "CST6CDT"
because in some countries they follow CDT in summer and CST in winter
public static String getDateInCST() {
Calendar calendar = Calendar.getInstance();
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
formatter.setTimeZone(TimeZone.getTimeZone( "CST6CDT"));
String strdate = formatter.format(calendar.getTime());
TimeZone.getAvailableIDs();
return strdate;
}
Problem is when you print date obj it call toString method and it will print in your machines default time zone. Try this code and see difference.
Calendar currentdate = Calendar.getInstance();
String strdate = null;
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ssz");
strdate = formatter.format(currentdate.getTime());
System.out.println("strdate=>" + strdate);
TimeZone obj = TimeZone.getTimeZone("CST");
formatter.setTimeZone(obj);
strdate = formatter.format(currentdate.getTime());
Date theResult = formatter.parse(strdate);
System.out.println("The current time in India is :: " +currentdate.getTime());
System.out.println("The date and time in :: " + obj.getDisplayName() + "is ::" + theResult);
System.out.println("The date and time in :: " + obj.getDisplayName() + "is ::" + strdate);
First message, don’t handle your date and time as strings in your code. Just as you don’t handle numbers and Boolean values as strings (I hope). Use proper date-time objects.
java.time
Sometimes we get date and time as string input. It may be from a text file, from the user or from data exchange with another system, for example. In those cases parse into a proper date-time object first thing. Second message, use java.time, the modern Java date and time API, for your date and time work.
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
String input = "2015-11-01 01:00:00";
ZonedDateTime nyTime = LocalDateTime.parse(input, formatter)
.atZone(ZoneId.of("America/New_York"));
System.out.println("Time in New York: " + nyTime);
Output from this snippet is:
Time in New York: 2015-11-01T01:00-04:00[America/New_York]
To convert to GMT:
OffsetDateTime gmtTime = nyTime.toOffsetDateTime()
.withOffsetSameInstant(ZoneOffset.UTC);
System.out.println("GMT Time: " + gmtTime);
GMT Time: 2015-11-01T05:00Z
If you need to give string output, format using a date-time formatter. Here’s an example of formatting for an American audience:
DateTimeFormatter userFormatter
= DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
.withLocale(Locale.US);
String formattedDateTime = gmtTime.format(userFormatter);
System.out.println("GMT Time formatted for user: " + formattedDateTime);
GMT Time formatted for user: Nov 1, 2015, 5:00:00 AM
You additionally asked:
Between the two results below, which one should you take?
I understand that you ask because both are valid answers. On November 1, 2015 summer time (DST) ended at 2 AM. That is, after 01:59:59 came 01:00:00 a second time. So when we have got 2015-11-01 01:00:00 as input, it is ambiguous. It could be in Eastern Daylight Time, equal to 05:00 GMT, or it could be in Eastern Standard Time, one hour later, hence equal to 06:00 GMT. There is no way that I can tell you which of them is correct in your case. You may control which result you get using withEarlierOffsetAtOverlap() or withLaterOffsetAtOverlap(). Above we got the DST interpretation. So to get the standard time interpretation:
nyTime = nyTime.withLaterOffsetAtOverlap();
System.out.println("Alternate time in New York: " + nyTime);
Alternate time in New York: 2015-11-01T01:00-05:00[America/New_York]
We notice that the hour of day is still 01:00, but the offset is now -05:00 instead of -04:00. This also gives us a different GMT time:
GMT Time: 2015-11-01T06:00Z
GMT Time formatted for user: Nov 1, 2015, 6:00:00 AM
Avoid SimpleDateFormat and friends
While the other answers are generally correct, the classes DateFormat, SimpleDateFormat, Date and Calendar used there are poorly designed and long outdated. The first two are particularly troublesome. I recommend you avoid all of them. I frankly find the modern API so much nicer to work with.
Link
Oracle tutorial: Date Time explaining how to use java.time.
Please refer to below mentioned code.
DateFormat utcConverter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
utcConverter.setTimeZone(TimeZone.getTimeZone("GMT"));
String sampleDateTime = "2015-11-01 01:00:00";
DateFormat nyConverter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
nyConverter.setTimeZone(TimeZone.getTimeZone("EST"));
Calendar nyCal = Calendar.getInstance();
nyCal.setTime(nyConverter.parse(sampleDateTime));
System.out.println("NY TIME :" +nyConverter.format(nyCal.getTime()));
System.out.println("GMT TIME :" +utcConverter.format(nyCal.getTime()));
2020 Answer Here
If you want the new java.time.* feature but still want to mess with java.util.Date:
public static Date convertBetweenTwoTimeZone(Date date, String fromTimeZone, String toTimeZone) {
ZoneId fromTimeZoneId = ZoneId.of(fromTimeZone);
ZoneId toTimeZoneId = ZoneId.of(toTimeZone);
ZonedDateTime fromZonedDateTime =
ZonedDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()).withZoneSameLocal(fromTimeZoneId);
ZonedDateTime toZonedDateTime = fromZonedDateTime
.withZoneSameInstant(toTimeZoneId)
.withZoneSameLocal(ZoneId.systemDefault())
;
return Date.from(toZonedDateTime.toInstant());
}
for java.sql.Timestamp
public static Timestamp convertBetweenTwoTimeZone(Timestamp timestamp, String fromTimeZone, String toTimeZone) {
ZoneId fromTimeZoneId = ZoneId.of(fromTimeZone);
ZoneId toTimeZoneId = ZoneId.of(toTimeZone);
LocalDateTime localDateTimeBeforeDST = timestamp.toLocalDateTime();
ZonedDateTime fromZonedDateTime = ZonedDateTime.of(localDateTimeBeforeDST, fromTimeZoneId);
ZonedDateTime toZonedDateTime = fromZonedDateTime.withZoneSameInstant(toTimeZoneId);
return Timestamp.valueOf(toZonedDateTime.toLocalDateTime());
}
For google calendar API
private String getFormatedDate(Date date)
{
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss+05:30");
df.setTimeZone(TimeZone.getTimeZone("GMT+05:30"));
return df.format(date);
}

Categories