In my project, I have get the API response in json format. I get a string value of time in UTC time format like this Jul 16, 2013 12:08:59 AM.
I need to change this into Local time.
That is where ever we use this the app needs to show the local time. How to I do this?
Here is some Code I have tried:
String aDate = getValue("dateTime", aEventJson);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss z");
simpleDateFormat.setTimeZone(TimeZone.getDefault());
String formattedDate = simpleDateFormat.format(aDate);
Assume aDate contains Jul 16, 2013 12:08:59 AM
Here's my attempt:
String dateStr = "Jul 16, 2013 12:08:59 AM";
SimpleDateFormat df = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss a", Locale.ENGLISH);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = df.parse(dateStr);
df.setTimeZone(TimeZone.getDefault());
String formattedDate = df.format(date);
Also notice the "a" for the am/pm marker...
I should like to contribute the modern answer. While SimpleDateFormat was the class we had for parsing and formatting date-times in 2013 (apart from Joda-Time), it is now long outdated, and we have so much better in java.time or JSR-310, the modern Java date and time API that came out with Java 8 in 2014.
But most Android devices still don’t run Java 8, I hear you say. Fortunately you can still use the modern Java date and time API on them through the ThreeTenABP, the backport of JSR-310 to Android Java 7. Details are in this question: How to use ThreeTenABP in Android Project.
Now the code is:
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("MMM dd, uuuu hh:mm:ss a", Locale.ENGLISH);
String aDate = "Jul 16, 2013 12:08:59 AM";
String formattedDate = LocalDateTime.parse(aDate, formatter)
.atOffset(ZoneOffset.UTC)
.atZoneSameInstant(ZoneId.systemDefault())
.format(formatter);
System.out.println(formattedDate);
Since my computer is running Europe/Copenhagen time zone, which in July is 2 hours ahead of UTC, this prints
Jul 16, 2013 02:08:59 AM
Further points:
Since you have AM in your string, I assumed your hours are within AM, from 1 through 12. To parse and format them correctly you need lowercase h in the format pattern string. Uppercase H is for hour-of-day from 0 through 23.
Prefer to give an explcit locale to the formatter (whether SimpleDateFormat or DateTimeFormatter). If no locale is given, the formatter will use the device’s default locale. “Jul” and “AM” are in English, and your code may run nicely on many devices until one day it runs on a device with non-English locale and crashes, and you have a hard time figuring out why.
If you can, give the desired time zone explictly, for example as ZoneId.of("Asia/Kolkata"). The JVM’s default time zone may be changed by other parts of your program or other programs running in the same JVM, so is not reliable.
1.Local to UTC Converter
public static String localToUTC(String dateFormat, String datesToConvert) {
String dateToReturn = datesToConvert;
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
sdf.setTimeZone(TimeZone.getDefault());
Date gmt = null;
SimpleDateFormat sdfOutPutToSend = new SimpleDateFormat(dateFormat);
sdfOutPutToSend.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
gmt = sdf.parse(datesToConvert);
dateToReturn = sdfOutPutToSend.format(gmt);
} catch (ParseException e) {
e.printStackTrace();
}
return dateToReturn;
}
2. UTC to Local Converter
public static String uTCToLocal(String dateFormatInPut, String dateFomratOutPut, String datesToConvert) {
String dateToReturn = datesToConvert;
SimpleDateFormat sdf = new SimpleDateFormat(dateFormatInPut);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date gmt = null;
SimpleDateFormat sdfOutPutToSend = new SimpleDateFormat(dateFomratOutPut);
sdfOutPutToSend.setTimeZone(TimeZone.getDefault());
try {
gmt = sdf.parse(datesToConvert);
dateToReturn = sdfOutPutToSend.format(gmt);
} catch (ParseException e) {
e.printStackTrace();
}
return dateToReturn; }
//your UTC time var
long time = UTCtime;
//convert it
Time timeFormat = new Time();
timeFormat.set(time+TimeZone.getDefault().getOffset(time));
//use the value
long localTime = timeFormat.toMillis(true);
Use the following code.
TimeZone defaultTimeZone = TimeZone.getDefault();
String strDefaultTimeZone = defaultTimeZone.getDisplayName(false, TimeZone.SHORT);
//The code you use
String aDate = getValue("dateTime", aEventJson);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss z");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone(strDefaultTimeZone));
String formattedDate = simpleDateFormat.format(aDate);
This should work.
This is how i do it on android Build.VERSION.SDK_INT < 26
int offset = TimeZone.getDefault().getRawOffset();
String str_date='20:30 12-01-2021';
DateFormat formatter = new SimpleDateFormat("HH:mm dd-MM-yyy",Locale.US);
Date date = formatter.parse(str_date);
long utcTime = date.getTime() + (3600000*3);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm dd/MM/yyyy", Locale.US);
String dateStr = sdf.format(utcTime + offset);
System.out.println(dateStr);
As my server sends the time with -3 timezone i have to add (3600*3) to getTime and i save it into utcTime, this way utcTime is in UTC. And then i add to utcTime the offset of the phone current timezone.
In my case as my timezone is -3 its prints:
20:30 12/01/2021
But if i change my time zone the date also changes.
Use this code:
public static String stringDateWithTimezone(Date date, String pattern, TimeZone timeZone) {
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern, Locale.US);
if (timeZone != null) {
simpleDateFormat.setTimeZone(timeZone);
}
return simpleDateFormat.format(date);
} catch (Exception e) {
Timber.e(e);
return null;
}
}
call in another class:
String dateUtc = DateUtil.stringDateWithTimezone(new Date(), "yyyy-MM-dd hh:mm:ss", TimeZone.getTimeZone("UTC"));
Related
I need to convert a string that is in (HH:mm) format which is supposed to be in UTC time to the local TimeZone. How to add the present date to the string and convert it local time.
I have tried using the calendar
String utcTimeString = "06:00";
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.getDefault());
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Calendar now = Calendar.getInstance(Locale.getDefault());
now.setTime(sdf.parse(utcTimeString));
You are well advised to use the modern API for dates, times, time zones, offsets, calendars and more:
java.time
Doing so, it is pretty easy to
parse the time you receive
get the current date and
combine them to a date-time representation with a certain time zone
See this little example:
public static void main(String[] args) {
// create a time object from the String
LocalTime localTime = LocalTime.parse("06:00", DateTimeFormatter.ofPattern("HH:mm"));
// print it once in an ISO format
System.out.println(localTime.format(DateTimeFormatter.ISO_TIME));
// receive the date of today
LocalDate today = LocalDate.now();
// then use the date and the time object to create a zone-aware datetime object
ZonedDateTime zdt = LocalDateTime.of(today, localTime).atZone(ZoneId.of("UTC"));
// print it
System.out.println(zdt.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
}
The output is
06:00:00
2019-11-04T06:00:00Z[UTC]
Which you can format as desired using different DateTimeFormatters.
Try like the following.
public String getDateTimeInUTC(String yourTime){
Calendar cal = Calendar.getInstance();
SimpleDateFormat currentDate= new SimpleDateFormat("MMM dd, yyyy ");
String currentDateTime = currentDate.format(cal.getTime())+yourTime; // here concate your time with current date.
System.out.println("Current date with given time: "+currentDateTime);
SimpleDateFormat df = new SimpleDateFormat("MMM dd, yyyy HH:mm", Locale.ENGLISH);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = null;
try {
date = df.parse(currentDateTime);
} catch (ParseException e) {
e.printStackTrace();
}
df.setTimeZone(TimeZone.getDefault());
String formattedDate = df.format(date);
return formattedDate;
}
Call getDateTimeInUTC like below
String strTime = "12:10"; // your string time in HH:mm format
String finalDateTime = getDateTimeInUTC(strTime);
System.out.println("Final date-time in UTC: "+finalDateTime);
OUTPUT:
Current date with given time: Nov 04, 2019 12:10
Final date-time in UTC: Nov 04, 2019 18:10
You can Check this Out :
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
//change the format according to your need
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//Here you say to java the initial timezone. This is the secret
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
//Will print in UTC
System.out.println(sdf.format(calendar.getTime()));
//Here you set to your timezone
sdf.setTimeZone(TimeZone.getDefault());
//Will print on your default Timezone
System.out.println(sdf.format(calendar.getTime()));
I only have a date string, and I want to see the time in other TimeZone by it. So I did it like that:
String dateStr = "2014-05-15 16:14:58 PM";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
sdf.setTimeZone(TimeZone.getTimeZone("America/Denver"));
Date date = sdf.parse(dateStr);
System.out.println(date);
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
System.out.println(sdf1.format(date));
This is the current TimeZone in my computer:
The result that the code ran was that:
Fri May 16 06:14:58 CST 2014
2014-05-16 06:14:58 AM
The result is wrong, I had the right result by changing the TimeZone to "America/Denver" in my computer, and I saw that:
America/Denver —— 2014-05-15 02:14:58 AM
I don't know why it likes that?
But if I had a Date not a date String, I do that :
public static String getFormatedDateString(String _timeZone) {
TimeZone timeZone = null;
if (StringUtils.isEmpty(_timeZone)) {
timeZone = TimeZone.getDefault();
} else {
timeZone = TimeZone.getTimeZone(_timeZone);
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
sdf.setTimeZone(timeZone);
// TimeZone.setDefault(timeZone);
return sdf.format(new Date());
}
System.out.println("America/Denver —— " + getFormatedDateString("America/Denver"));
The result likes that:
------Asia/Shanghai------
2014-05-15 16:32:04 PM (current date)
America/Denver —— 2014-05-15 02:32:04 AM
This result is right.
So I was confused, I could't find the problem when I just have a date string and I want to know the time of other TimeZone. Could any body help me?
Date object in Java is independent of the concept of timezone.
What you want to do get the equivalent time in another timezone of a date string which is 'supposed' to be in your own timezone.
However, 2nd point appears backwards in your code:
String dateStr = "2014-05-15 16:14:58 PM";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
sdf.setTimeZone(TimeZone.getTimeZone("America/Denver"));
Date date = sdf.parse(dateStr);
What these 4 lines do is consider the date string as a point in time in "America/Denver" timezone.
When you parse it to the date object, it would give you the equivalent time in your own timezone.
You want it the other way round:
Hence staying close to your code (you can just use a single SimpleDateFormat instance effectively, which you can figure out later),
Drop the setTimezone on the first sdf:
String dateStr = "2014-05-15 16:14:58 PM";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
//sdf.setTimeZone(TimeZone.getTimeZone("America/Denver"));
Date date = sdf.parse(dateStr);
System.out.println(date);
Add the same setTimezone to the other sdf:
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
sdf1.setTimeZone(TimeZone.getTimeZone("America/Denver"));
System.out.println(sdf1.format(date));
Now, you are parsing your date String to a date in your current (JVM's) timezone. Then format the same date to a different timezone's String.
Output I get with the changed code (my JVM's timezone being IST):
Thu May 15 16:14:58 IST 2014 // Parsed the date string in IST
2014-05-15 04:44:58 AM // Equivalent time in Denver
In the below code getting parsing error:please help.
DateFormat converter = new SimpleDateFormat("dd/MM/yyyy:HH:mm:ss");
converter.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat formatter = new SimpleDateFormat("E, MMM dd yyyy");
Date date = formatter.parse(converter.format(new Date()));
I will try to explain what JB Nizet and others tried in the comments. In a simplified manner to make it understandable.
A Date is nothing else but a long which represents the time since epoch and a nice toString() method. Basically.
So if you create a Date date = new Date(); it sets the date's time value to System.currentTimeMillis();, nothing more, nothing less.
The interesting thing is that the Unix time is already "in UTC (=GMT)", if you want to say so.
If you now print the date like this
Date date = new Date();
System.out.println(date);
you implicitly call date.toString();.
This toString() can be seen as follows:
public String toString() {
return new SimpleDateFormat("E MMM dd HH:mm:ss z YYYY").format(this);
}
The SimpleDateFormat uses by default YOUR timezone. But it doesn't change the value of the date at all, it just prints it in another way.
If you now want to see the date in GMT you can simply set the SimpleDateFormat yourself:
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("E MMM dd HH:mm:ss z YYYY");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(sdf.format(date));
To push it further you could now write a simple static method somewhere to print dates in specific timezones:
public static void printDate(Date date) {
printDate(date, "GMT");
}
public static void printDate(Date date, String timeZone) {
printDate(date, TimeZone.getTimeZone(timeZone));
}
public static void printDate(Date date, TimeZone timeZone) {
SimpleDateFormat sdf = new SimpleDateFormat("E MMM dd HH:mm:ss z YYYY");
sdf.setTimeZone(timeZone);
System.out.println(sdf.format(date));
}
To see what we all are talking about (that the timestamp does never change) you can print both:
public static void printDate(Date date, TimeZone timeZone) {
SimpleDateFormat sdf = new SimpleDateFormat("E MMM dd HH:mm:ss z YYYY");
sdf.setTimeZone(timeZone);
System.out.println(sdf.format(date) + " has the timestamp " + date.getTime());
}
If we now do some simple tests we see these results:
Local Time:
Sat Feb 22 16:08:12 CET 2014 has the timestamp 1393081692749
GMT:
Sat Feb 22 15:08:12 GMT 2014 has the timestamp 1393081692749
PST:
Sat Feb 22 07:08:12 PST 2014 has the timestamp 1393081692749
As you can see the times are all correct for their timezones, and the timestamp itself is always the same.
So to answer your question: Your simple new Date();, as it's already written in the comments, already achieves what you want: the Date is always in UTC (which equals GMT).
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);
}
My first attempt was:
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
Date date = formatter.parse(string);
It throws ParseException, so I found this hack:
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
TimeZone timeZone = TimeZone.getTimeZone("Etc/GMT");
formatter.setTimeZone(timeZone);
Date date = formatter.parse(string);
It did not work either, and now I'm stuck. It parses without problems if I just change the timezone to "GMT".
edit: An example string to parse would be "2011-11-29 10:40:24 Etc/GMT"
edit2: I would prefer not to remove timezone information completely. I am coding a server that receives the date from an external user, so perhaps other dates will have other timezones.
To be more precise: This specific date I receive is from the receipt from the apple server after making an in app purchase on an iphone app, but I could also receive dates from other sources.
Don't know if this question is still relevant to you, but if you use Joda time, this'll work:
DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss ZZZ").parseDateTime(s)
Without Joda time the following will work (bit more work though):
String s = "2011-11-29 10:40:24 Etc/GMT";
// split the input in a date and a timezone part
int lastSpaceIndex = s.lastIndexOf(' ');
String dateString = s.substring(0, lastSpaceIndex);
String timeZoneString = s.substring(lastSpaceIndex + 1);
// convert the timezone to an actual TimeZone object
// and feed that to the formatter
TimeZone zone = TimeZone.getTimeZone(timeZoneString);
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
formatter.setTimeZone(zone);
// parse the timezoneless part
Date date = formatter.parse(dateString);
It didn't work for me either the thing is I tried setting TimeZone of SimpleDateFormatter to "Etc/GMT" and then formatted a new date here is the output:
2011-11-30 10:46:32 GMT+00:00
So Etc/GMT is being translated as GMT+00:00
If you really want to stick to parse "2011-09-02 10:26:35 Etc/GMT" then following will help too without even considering explicit Timezone change:
java.text.SimpleDateFormat isoFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss 'Etc/GMT'");
isoFormat.parse("2010-05-23 09:01:02 Etc/GMT");
Works fine.
Following code is working for me
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("Etc/GMT"));
try { System.out.println( sdf.parse("2011-09-02 10:26:35 Etc/GMT") );
} catch (ParseException e){
e.printStackTrace();
}