Convert Date/Time for Given Timezone - Java

Convert Date/Time for given Timezone - java

For me, the simplest way to do that is:

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
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()));

Java Date Time conversion to given timezone

with the help of @ole v.v's explanation i have separated the datetime value for two
1. time
2. timezone

then i used this coding to extract the datetime which is related to the given timezone

//convert datetime to give timezone 
private static String DateTimeConverter (String timeVal, String timeZone)
{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

SimpleDateFormat offsetDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");

offsetDateFormat2.setTimeZone(TimeZone.getTimeZone(timeZone));
String result =null;
try {
result = offsetDateFormat2.format(format.parse(timeVal));
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return result;
}

How to set time zone of a java.util.Date?

Use DateFormat. For example,

SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
isoFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = isoFormat.parse("2010-05-23T09:01:02");

Convert timestamp to Date time for a particular timezone

You cannot convert a timestamp to another timezone, cause timestamps are always GMT, they are a given moment in the line of time in the universe.

We humans are used to local time on our planet, so a timestamp can be formatted to be more human readable, and in that context it is converted to a local timezone.

Using legacy java.util.* packages, this is done as follows:

DateFormat tzFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
tzFormat.setTimeZone(TimeZone.getTimeZone("CET")); // Use whatever timezone
System.out.println(tzFormat.format(date));

If you need to make "math" over the timestamp on local timezone (like, tomorrow at 8:00 local timezone), then the situation is more complex.

To do this you can resort to a number of hacks (like parsing or modifying the string obtained with the method above), or use the new Java date & time classes that have a specific class to deal with date and time in local time zones:

Instant timestamp = Instant.ofEpochMilli(inputValue);
ZonedDateTime romeTime = timestamp.atZone(ZoneId.of("Europe/Rome"));

Note how this second example uses "Europe/Rome" and not generically "CET". This is very important if you're planning to deal with timezones where DST is used, cause the DST change day (or if they use DST or not) may change from country to country even if they are in the same timezone.

How to get the current date and time of your timezone in Java?

Date is always UTC-based... or time-zone neutral, depending on how you want to view it. A Date only represents a point in time; it is independent of time zone, just a number of milliseconds since the Unix epoch. There's no notion of a "local instance of Date." Use Date in conjunction with Calendar and/or TimeZone.getDefault() to use a "local" time zone. Use TimeZone.getTimeZone("Europe/Madrid") to get the Madrid time zone.

... or use Joda Time, which tends to make the whole thing clearer, IMO. In Joda Time you'd use a DateTime value, which is an instant in time in a particular calendar system and time zone.

In Java 8 you'd use java.time.ZonedDateTime, which is the Java 8 equivalent of Joda Time's DateTime.

Date TimeZone conversion in java?

The catch here is that the DateFormat class has a timezone. Try this example instead:

    SimpleDateFormat sdfgmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdfgmt.setTimeZone(TimeZone.getTimeZone("GMT"));

SimpleDateFormat sdfmad = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdfmad.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));

String inpt = "2011-23-03 16:40:44";
Date inptdate = null;
try {
inptdate = sdfgmt.parse(inpt);
} catch (ParseException e) {e.printStackTrace();}

System.out.println("GMT:\t\t" + sdfgmt.format(inptdate));
System.out.println("Europe/Madrid:\t" + sdfmad.format(inptdate));

convert date and time in any timezone to UTC zone

You cannot "convert that date values" to other timezones or UTC. The type java.util.Date does not have any internal timezone state and only refers to UTC by spec in a way which cannot be changed by user (just counting the milliseconds since UNIX epoch in UTC timezone leaving aside leapseconds).

But you can convert the formatted String-representation of a java.util.Date to another timezone. I prefer to use two different formatters, one per timezone (and pattern). I also prefer to use "Asia/Kolkata" in your case because then it will universally works (IST could also be "Israel Standard Time" which will be interpreted differently in Israel):

DateFormat formatterIST = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
formatterIST.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata")); // better than using IST
Date date = formatterIST.parse("15-05-2014 00:00:00");
System.out.println(formatterIST.format(date)); // output: 15-05-2014 00:00:00

DateFormat formatterUTC = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
formatterUTC.setTimeZone(TimeZone.getTimeZone("UTC")); // UTC timezone
System.out.println(formatterUTC.format(date)); // output: 14-05-2014 18:30:00

// output in system timezone using pattern "EEE MMM dd HH:mm:ss zzz yyyy"
System.out.println(date.toString()); // output in my timezone: Wed May 14 20:30:00 CEST 2014

Convert string to appropriate date with timezone java

You need TWO format objects, one for parsing and another one for printing because you use two different timezones, see here:

// h instead of H  because of AM/PM-format
DateFormat parseFormat = new SimpleDateFormat("M/dd/yyyy hh:mm:ss aaa XXX");
Date dt = null;
try {
dt = parseFormat.parse("3/15/2013 3:01:53 PM -06:00");
}catch (ParseException e) {
e.printStackTrace();
}

DateFormat printFormat = new SimpleDateFormat("M/dd/yyyy hh:mm:ss aaa XXX");
printFormat.setTimeZone(TimeZone.getTimeZone("GMT-05"));
String newDateString = printFormat.format(dt);
System.out.println(newDateString);

Output: 3/15/2013 04:01:53 PM -05:00

If you want HH:mm:ss (24-hour-format) then you just replace

hh:mm:ss aaa 

by

HH:mm:ss

in printFormat-pattern.


Comment on other aspects of question:

A java.util.Date has no internal timezone and always refers to UTC by spec. You cannot change it inside this object. A timezone conversion is possible for the formatted string, however as demonstrated in my code example (you wanted to convert to zone GMT-05).

The question then switches to the new requirement to print the Date-object in ISO-format using UTC timezone (symbol Z). This can be done in formatting by replacing the pattern with "yyyy-MM-dd'T'HH:mm:ssXXX" and explicitly setting the timezone of printFormat to GMT+00. You should clarify what you really want as formatted output.

About java.util.GregorianCalendar: Setting the timezone here is changing the calendar-object in a programmatical way, so it affects method calls like calendar.get(Calendar.HOUR_OF_DAY). This has nothing to do with formatting however!

convert string to date without changing timezone in the string using java

Just omit the timezone format from the end of the String (letter Z).
For example, this will print Thu Nov 12 06:30:00 CET 2020

String s = "2020-11-12T6:30:00-0800";
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
var date = format.parse(s);
System.out.println(date);

But if I add the letter Z at the end, it will interpret the given timezone and change time to my local timezone, when printed. So this will print Thu Nov 12 15:30:00 CET 2020

String s = "2020-11-12T6:30:00-0800";
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
var date = format.parse(s);
System.out.println(date);

More about the patterns can be found in the JavaDoc of SimpleDateFormat.



Related Topics



Leave a reply



Submit