Java 8 Convert Utc Time to Edt/Est So That Date Remains the Same

Java 8 Convert UTC time to EDT/EST so that date remains the same

You can do it by converting to LocalDateTime and back to ZonedDateTime with specified time zone:

ZonedDateTime zoned = ZonedDateTime.now();
LocalDateTime local = zoned.toLocalDateTime();
ZonedDateTime newZoned = ZonedDateTime.of(local, ZoneId.of("America/New_York"));

Converting date from UTC to EST in Java?

Yesterday occasionally I wrote the following method that can help you:

private Date shiftTimeZone(Date date, TimeZone sourceTimeZone, TimeZone targetTimeZone) {
Calendar sourceCalendar = Calendar.getInstance();
sourceCalendar.setTime(date);
sourceCalendar.setTimeZone(sourceTimeZone);

Calendar targetCalendar = Calendar.getInstance();
for (int field : new int[] {Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, Calendar.HOUR, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND}) {
targetCalendar.set(field, sourceCalendar.get(field));
}
targetCalendar.setTimeZone(targetTimeZone);

return targetCalendar.getTime();
}

Now you just have to format the date. Use SimpleDateFormat for this. Here is the example:

DateFormat format = new SimpleDateFormat("dd/MM/yy hh:mm a");
format.format(date);

Java 8 Convert given time and time zone to UTC time

You are looking for ZonedDateTime class in Java8 - a complete date-time with time-zone and resolved offset from UTC/Greenwich. In terms of design, this class should be viewed primarily as the combination of a LocalDateTime and a ZoneId. The ZoneOffset is a vital, but secondary, piece of information, used to ensure that the class represents an instant, especially during a daylight savings overlap.

For example:

ZoneId australia = ZoneId.of("Australia/Sydney");
String str = "2015-01-05 17:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime localtDateAndTime = LocalDateTime.parse(str, formatter);
ZonedDateTime dateAndTimeInSydney = ZonedDateTime.of(localtDateAndTime, australia );

System.out.println("Current date and time in a particular timezone : " + dateAndTimeInSydney);

ZonedDateTime utcDate = dateAndTimeInSydney.withZoneSameInstant(ZoneOffset.UTC);

System.out.println("Current date and time in UTC : " + utcDate);

Convert Time from one time zone to another using Java 8 Time

It seems that whatever service you found was being over-helpful in interpreting what you meant and assumed North American Eastern Daylight Time (EDT) when you specified EST (Eastern Standard Time). Most, not all of the places using EST as standard time are using daylight saving time and hence were on EDT or offset UTC-04:00 on the date you use, April 30, 2015.

If it makes sense in your situation, you should always prefer to give time zone in the region/city format, as Asia/Kolkata and America/New_York. If you intended Eastern Time as in New York or Montréal, one may say that your “time zone” of GMT-5:00 was wrong and the cause of your unexpected result.

So your code becomes for example:

    String inputDate = "2015/04/30 13:00";
DateTimeFormatter sourceFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm", Locale.US);
LocalDateTime local = LocalDateTime.parse(inputDate, sourceFormatter);
// local : 2015-04-30T13:00
//Combining this local date-time with a time-zone to create a ZonedDateTime.
ZonedDateTime zoned = local.atZone(ZoneId.of("Asia/Kolkata"));
// zoned : 2015-04-30T13:00+05:30[Asia/Kolkata]
ZonedDateTime zonedUS = zoned.withZoneSameInstant(ZoneId.of("America/Montreal"));
// zonedUS : 2015-04-30T03:30-04:00[America/Montreal]

I have made one other change: When using the modern classes from java.time, there is no point in also using the outdated TimeZone class, so I have taken that out. The code is slightly simpler, and more importantly, ZoneId.of(String) includes validation of your time zone string so you will discover any spelling error in the time zone name (like when I just happened to type a ( instead of the / in Asia/Kolkata — such happens all the time).

Most of the above has already been said in comments by Jon Skeet and others. I thought it deserved to go into an answer so it’s plain to see that the question has been answered.

UTC timestamp not returning correct time

This is the problem:

TimeZone.getTimeZone("America/New York")

That's not a valid time zone ID. You want:

TimeZone.getTimeZone("America/New_York")

Note the underscore. Personally I think it's a shame that getTimeZone gives no indication that it hasn't actually found the time zone you've asked for, but it's been that way for a long time :(

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

Converting EST to EDT or vice versa in Java

How to retrieve TimeZone from java.util.Date instance?

There's no such thing. A Date just represents a number of milliseconds since the Unix epoch, which was midnight on January 1st 1970 UTC. It's not associated with a particular calendar system or time zone. To put it another way, if a friend and I are on the phone together (with a zero latency ;) and I click my fingers, we would both agree on the Date at which that click too place - even if I'm using the Gregorian calendar and he's using the Julian calendar, and even if I'm in London and he's in New York. It's the same instant in time.

How to know whether Daylight savings is applicable?, I suppose I can know it by doing timeZone.getDSTSavings, but problem I am facing is that even if I make my system's date as Feb 1 2012, still I am getting the value as positive (I guess 3600000)

Ideally, use Joda Time instead of java.util.Date/Calendar/TimeZone, but within TimeZone you can use TimeZone.getOffset(long) to find the offset from UTC, or TimeZone.inDaylightTime(Date) to just give you a yes/no answer.

How to convert EST time to EDT or vice versa?

Usually that's an invalid question - because at any one instance in time, either EST or EDT applies. You normally convert from one time zone to another, and "EDT" and "EST" aren't different time zones - they're different offsets within the same time zone. The fact that you're asking for this suggests that you may be modelling your data incorrectly to start with (which is unfortunately easy to do with date/time values). Please give us more information and we may be able to help you more.

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


Related Topics



Leave a reply



Submit