Date and Time Conversion to Some Other Timezone in Java

Date and time conversion to some other Timezone in java

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());

Convert date to different timezone

When you print the date using System.out.println(date); or System.out.println(instance2.getTime());, the Date returned by instance2.getTime() is TimeZone independent and always prints the date in local timezone.

Instead you may want to use DateFormat/SimpleDateFormat:

  DateFormat formatter= new SimpleDateFormat("MM/dd/yyyy HH:mm:ss Z");
formatter.setTimeZone(TimeZone.getTimeZone("Europe/London"));
System.out.println(formatter.format(date));

formatter.setTimeZone(TimeZone.getTimeZone("Europe/Athens"));
System.out.println(formatter.format(instance2.getTime()))

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()));

converting date from one time zone to other time zone in java

tl;dr

Use modern java.time classes, specifically ZonedDateTime and ZoneId. See Oracle Tutorial.

ZonedDateTime                         // Represent a date and time-of-day in a specific time zone.
.now( // Capture the current moment as seen in the wall-clock time used by the people of a particular region (a time zone).
ZoneId.of( "Pacific/Auckland" ) // Specify time zone using proper name in `Continent/Region` format. Never use 3-4 letter pseudo-zone such as IST or PST or EST.
) // Returns a `ZonedDateTime` object.
.withZoneSameInstant( // Adjust from one time zone to another. Same point on the timeline, same moment, but different wall-clock time.
ZoneId.of( "Africa/Tunis" )
) // Returns a new fresh `ZonedDateTime` object rather than altering/“mutating” the original, per immutable objects pattern.
.toString() // Generate text in standard ISO 8601 format, extended to append name of zone in square brackets.

2018-09-18T21:47:32.035960+01:00[Africa/Tunis]

For UTC, call ZonedDateTime::toInstant.

Avoid 3-Letter Time Zone Codes

Avoid those three-letter time zone codes. They are neither standardized nor unique. For example, your use of "IST" may mean India Standard Time, Irish Standard Time, and maybe others.

Use proper time zone names. The definition of time zones and their names change frequently, so keep your source up-to-date. For example the old "Asia/Calcutta" is now "Asia/Kolkata". And not just names; governments are notorious for changing the rules/behavior of a time zone, occasionally at the last minute.

Avoid j.u.Date

Avoid using the bundled java.util.Date and Calendar classes. They are notoriously troublesome and will be supplanted in Java 8 by the new java.time.* package (which was inspired by Joda-Time).

java.time

Instant

Learn to think and work in UTC rather than your own parochial time zone. Logging, data-exchange, and data-storage should usually be done in UTC.

Instant instant = Instant.now() ;  // Capture the current moment in UTC.

instant.toString(): 2018-09-18T20:48:43.354953Z

ZonedDateTime

Adjust into a time zone. Same moment, same point on the timeline, different wall-clock time. Apply a ZoneId (time zone) to get a ZonedDateTime object.

ZoneId zMontreal = ZoneId.of( "America/Montreal" ) ;  
ZonedDateTime zdtMontreal = instant.atZone( zMontreal ) ; // Same moment, different wall-clock time.

We can adjust again, using either the Instant or the ZonedDateTime.

ZoneId zKolkata = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdtKolkata = zdtMontreal.withZoneSameInstant​( zKolkata ) ;

ISO 8601

Calling toString on any of these classes produce text in standard ISO 8601 class. The ZonedDateTime class extends the standard wisely by appending the name of the time zone in square brackets.

When exchanging date-time values as text, always use ISO 8601 formats. Do not use custom formats or localized formats as seen in your Question.

The java.time classes use the standard formats by default for both parsing and generating strings.

Instant instant = Instant.parse( "2018-01-23T01:23:45.123456Z" ) ;

Using standard formats avoids all that messy string manipulation seen in the Question.

Adjust to UTC

You can always take a ZonedDateTime back to UTC by extracting a Instant.

Instant instant = zdtKolkata.toInstant() ;

DateTimeFormatter

To represent your date-time value in other formats, search Stack Overflow for DateTimeFormatter class. You will find many examples and discussions.


UPDATE: The Joda-Time project is now in maintenance-mode, and advises migration to the java.time classes. I am leaving this section intact as history.

Joda-Time

Beware of java.util.Date objects that seem like they have a time zone but in fact do not. In Joda-Time, a DateTime does indeed know its assigned time zone. Generally should specify a desired time zone. Otherwise, the JVM's default time zone will be assigned.

Joda-Time uses mainly immutable objects. Rather than modify an instance, a new fresh instance is created. When calling methods such as toDateTime, a new fresh DateTime instance is returned leaving the original object intact and unchanged.

//DateTime now = new DateTime(); // Default time zone automatically assigned.

// Convert a java.util.Date to Joda-Time.
java.util.Date date = new java.util.Date();
DateTime now = new DateTime( date ); // Default time zone automatically assigned.

DateTimeZone timeZone = DateTimeZone.forID( "Asia/Kolkata" );
DateTime nowIndia = now.toDateTime( timeZone );

// For UTC/GMT, use built-in constant.
DateTime nowUtcGmt = nowIndia.toDateTime( DateTimeZone.UTC );

// Convert from Joda-Time to java.util.Date.
java.util.Date date2 = nowIndia.toDate();

Dump to console…

System.out.println( "date: " + date );
System.out.println( "now: " + now );
System.out.println( "nowIndia: " + nowIndia );
System.out.println( "nowUtcGmt: " + nowUtcGmt );
System.out.println( "date2: " + date2 );

When run…

date: Sat Jan 25 16:52:28 PST 2014
now: 2014-01-25T16:52:28.003-08:00
nowIndia: 2014-01-26T06:22:28.003+05:30
nowUtcGmt: 2014-01-26T00:52:28.003Z
date2: Sat Jan 25 16:52:28 PST 2014

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.

    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

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;
}

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 date to another timezone in JavaScript

Here is the one-liner:

function convertTZ(date, tzString) {
return new Date((typeof date === "string" ? new Date(date) : date).toLocaleString("en-US", {timeZone: tzString}));
}

// usage: Asia/Jakarta is GMT+7
convertTZ("2012/04/20 10:10:30 +0000", "Asia/Jakarta") // Tue Apr 20 2012 17:10:30 GMT+0700 (Western Indonesia Time)

// Resulting value is regular Date() object
const convertedDate = convertTZ("2012/04/20 10:10:30 +0000", "Asia/Jakarta")
convertedDate.getHours(); // 17

// Bonus: You can also put Date object to first arg
const date = new Date()
convertTZ(date, "Asia/Jakarta") // current date-time in jakarta.



Related Topics



Leave a reply



Submit