Timestamp conversion in java - java

I am converting timestamp to date format yyyy-MM-dd HH:mm:ss.SSS and I am using America/New_York as TimeZone. Whenever I convert the timestamp into the date it shows one hour less than usual date and time. How to resolve this in java?
Here's the code:
String timestamp = "1431941838000";
long time = Long.valueOf(timestamp);
Date currentDate = new Date(time);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
TimeZone zone = TimeZone.getTimeZone("America/New_York");
df.setTimeZone(zone);
String finale = df.format(currentDate);

Try to using EST to replace America/New_York like
TimeZone zone = TimeZone.getTimeZone("EST");
Updated
It's My Test code:
String timestamp = "1431941838000";
long time = Long.valueOf(timestamp);
Date currentDate = new Date(time);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
TimeZone zoneNewYork = TimeZone.getTimeZone("America/New_York");
df.setTimeZone(zoneNewYork);
String finale = df.format(currentDate);
System.out.println(finale);
TimeZone zoneEst = TimeZone.getTimeZone("EST");
df.setTimeZone(zoneEst);
finale = df.format(currentDate);
System.out.println(finale);
And My result as bellow:
2015-05-18 05:37:18.000
2015-05-18 04:37:18.000

You have an extra point in this line:
TimeZone zone = TimeZone.getTimeZone("America/New_York").;
// ^ here!!!
UPDATE if you dont get any error, the output must be the correct:
EST is UTC - 5 hours. America/New_York is EST in the winter and E*D*T in the summer, so check if String timestamp = "1431941838000"; is winter or summer...
This code works ok:
Calendar calNewYork = Calendar.getInstance();
calNewYork.setTimeZone(TimeZone.getTimeZone("America/New_York"));
System.out.println("Time in New York: " + calNewYork.get(Calendar.HOUR_OF_DAY) + ":"
+ calNewYork.get(Calendar.MINUTE));
Use this to check your time:
long timestamp = "1431941838000";
Calendar calNewYork = Calendar.getInstance();
calNewYork.setTimeZone(TimeZone.getTimeZone("America/New_York"));
calNewYork.setTime(new Date(timestamp));
System.out.println("Time in New York: " + calNewYork.get(Calendar.HOUR_OF_DAY) + ":"
+ calNewYork.get(Calendar.MINUTE));

Related

How to get perfect UTC Time in java/android?

I am trying to get UTC time in my application but unfortunately every time I am getting my current emulator Date and Time Instead of UTC.
Tried,
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
ZonedDateTime utcTime = ZonedDateTime.now(ZoneOffset.UTC);
DateTime now = DateTime.now(DateTimeZone.UTC);
My code:
//create UTC time
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println("DATETIME ==> " + cal.getTime());
ZonedDateTime utcTime = ZonedDateTime.now(ZoneOffset.UTC);
System.out.println("DATETIME = " + utcTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
DateTime now = DateTime.now(DateTimeZone.UTC);
System.out.println("DATETIME = " + now);
Any help highly appreciated.
Try this code:
private String getCurrentDateTimeAccordingToUTC(String format) {
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
return simpleDateFormat.format(date);
}
String date = getCurrentDateTimeAccordingToUTC("dd-MM-yyyy hh:mm:ss a");
Log.e("date--","inUTC--:"+date);

Convert current GMT time into CST timezone using java

I am trying to convert current GMT time to CST time using JDK8. But my code always returns the same time for both the timezones. I also verified getAvailableIDs() has "CST".
Calendar cal = Calendar.getInstance();
TimeZone timeZone = TimeZone.getTimeZone("GMT");
cal.setTimeZone(timeZone);
// System.out.println("GMT time = " + cal.getTime());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(timeZone);
String gmtDateStr = sdf.format(cal.getTime());
System.out.println("Formatted GMT time = " + gmtDateStr);
// To CST
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
TimeZone cst = TimeZone.getTimeZone("CST");
sdf2.setTimeZone(cst);
Date cstDate = sdf2.parse(gmtDateStr);
// System.out.println("PARSED CST DATE = " + cstDate);
Calendar cal2 = new GregorianCalendar();
cal2.setTime(cstDate);
cal2.setTimeZone(cst);
String cstDateStr = sdf2.format(cal2.getTime());
// System.out.println("cal2 time = " + cal2.getTime());
System.out.println("FORMATTED CST DATE = " + cstDateStr);
What is wrong here? Can any one provide me an answer?
You don't have to do all of this conversion to get time in your preferred timezone. You can simply do following..
Calendar cal = Calendar.getInstance();
TimeZone timeZone = TimeZone.getTimeZone("GMT");
cal.setTimeZone(timeZone);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(timeZone);
String gmtDateStr = sdf.format(cal.getTime());
System.out.println("Formatted GMT time = " + gmtDateStr);
// To CST
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
TimeZone cst = TimeZone.getTimeZone("CST");
sdf2.setTimeZone(cst);
System.out.println("FORMATTED CST DATE = " + sdf2.format(cal.getTime()));
Java 8 java.time doesn't find a zone identified by CST
ZoneId cst = ZoneId.of("CST");
results in java.time.zone.ZoneRulesException: Unknown time-zone ID: CST. This makes sense as there is Central Standard Time in North America, China Standard Time, and possibly other.
If you mean Central Standard Time in North America which is represented by America/Chicago:
ZoneId gmt = ZoneId.of("GMT");
ZoneId cst = ZoneId.of("America/Chicago");
ZonedDateTime gmtTime = ZonedDateTime.now(gmt);
ZonedDateTime cstTime = gmtTime.withZoneSameInstant(cst);
What is wrong with your code is all those calls to Calendar.getTime(). This returns a Date instance, and those objects do not have the concept of a time zone. So it is useless to set the time zone in the Calendar instances because you then discard that info when converting to Date.
Just specify the time zone in your formatter, as in Yogesh Badke's answer.

codenameone convert time to utc

I am working on codename one project and I am struggling to convert device time to UTC.
I use this code :
Calendar cal = Calendar.getInstance();
System.out.println(cal.getTimeZone());
TimeZone tzUTC = TimeZone.getTimeZone("UTC");
com.codename1.l10n.DateFormat dtfmt = new com.codename1.l10n.SimpleDateFormat("EEE, yyyy-MM-dd KK:mm a z");
dtfmt.setTimeZone(tzUTC);
System.out.println("UTC: " + dtfmt.format(cal.getTime()));
and codename one reject the setTImeZone method.
I use java.text.DateFormat but when I run it, condename one cant compile it also.
It may not really answer your real question, but the following works for me:
Calendar cal = Calendar.getInstance();
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG);
TimeZone tzUtc = TimeZone.getTimeZone("UTC");
df.setTimeZone(tzUtc);
System.out.println("UTC: " + df.format(cal.getTime()));
I don’t know com.codename1.l10n.DateFormat, so I’m sorry I cannot help you there.
Use:
java.util.Calendar cal = java.util.Calendar.getInstance();
TimeZone tz = cal.getTimeZone();
cal.setTime(new Date(System.currentTimeMillis() - tz.getRawOffset()));
com.codename1.l10n.DateFormat dtfmt = new com.codename1.l10n.SimpleDateFormat("EEE, yyyy-MM-dd KK:mm a");
System.out.println("UTC: " + dtfmt.format(cal.getTime()));
Then append UTC to the string as the value is always UTC.
Was using Shai's solution but noticed that it wasn't giving the correct UTC time when the device timezone was in daylight savings time. Below is a more general solution using tz.getOffset() instead of tz.getRawOffset(). Seems like there should be simpler way!
L10NManager l10n = L10NManager.getInstance();
long sysRtnTime = System.currentTimeMillis() / 1000L;
Date errorDate = new Date(sysRtnTime * 1000L);
Date currentDate = new Date();
String deviceTime = l10n.formatDateTime(errorDate);
Calendar c = Calendar.getInstance();
long unixtime = errorDate.getTime();
TimeZone tz = c.getTimeZone();
// to get offset, we need era, year, month, day, dayOfWeek,millis
SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
SimpleDateFormat monthDateFormat = new SimpleDateFormat("MM");
SimpleDateFormat dayDateFormat = new SimpleDateFormat("dd");
SimpleDateFormat dayOfWeekDateFormat = new SimpleDateFormat("F");
SimpleDateFormat millisDateFormat = new SimpleDateFormat("S");
int year = Integer.parseInt(yearFormat.format(currentDate));
int month = Integer.parseInt(monthDateFormat.format(currentDate));
int day = Integer.parseInt(dayDateFormat.format(currentDate));
int dayOfWeek = Integer.parseInt(dayOfWeekDateFormat.format(currentDate));
int millis = Integer.parseInt(millisDateFormat.format(currentDate));
// c.setTime(new Date(unixtime - tz.getRawOffset())); // c in UTC only if device not DST
month = month - 1; // since getOffset assume 0 = Jan and 11 = Dec
c.setTime(new Date(unixtime - tz.getOffset(1, year, month, day, dayOfWeek, millis))); // c in UTC (even if device in DST)
Date cDateUTC = c.getTime(); // sDate in UTC
String timeInUTC = serverDateFormat.format(cDateUTC);
Log.p("Time (in device timezone): " + deviceTime);
Log.p("Time (in UTC): " + timeInUTC);

How to add device GMT time to a specific time?

I am getting a time from API like this "00:00" and I want to add Device GMT time to received time from API.
I am using following code for getting GMT Time of device
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"),
Locale.US);
Date currentLocalTime = calendar.getTime();
DateFormat date = new SimpleDateFormat("dd:MM:yyyy HH:mm z");
String localTime = date.format(currentLocalTime);
Log.v("GMT time:", localTime + "");
Is there any inbuilt method to add GMT time to a specific time?
Maybe you can try something like this
public static void main(final String[] args) throws Exception {
Date date = new Date();
DateFormat localDf = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
DateFormat gmtDf = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
DateFormat nyDf = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
gmtDf.setTimeZone(TimeZone.getTimeZone("GMT"));
nyDf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
System.out.println("local : " + localDf.format(date));
System.out.println("GMT : " + gmtDf.format(date));
System.out.println("NY : " + nyDf.format(date));
}
You can try like this:
TimeZone gmtTime = TimeZone.getTimeZone("GMT+00");
date.setTimeZone(gmtTime);
String localTime = date.format(currentLocalTime);
Date and time conversion to some other Timezone in java

Java convert date to EST timezone to respecting DST

I want to get the current date converted to America/Montreal timezone. I'm doing it like this:
Date date = new Date();
TimeZone timeZone = TimeZone.getTimeZone ("America/Montreal");
Calendar cal = new GregorianCalendar(timeZone);
cal.setTime(date);
String whatIWant = "" + cal.get(Calendar.HOUR_OF_DAY) + ':'+
cal.get(Calendar.MINUTE)+ ':'+ cal.get(Calendar.SECOND);
log.info(whatIWant);
The conversion is just fine but I was wondering how robust this code is. What will happen when in no daylight saving?
That code is fine. Java automatically takes winter time or summer time into account.
You could also do this by using a DateFormat object to convert the date to a string, setting the desired time zone on the DateFormat object:
Date date = new Date();
DateFormat df = new SimpleDateFormat("HH:mm:ss");
// Tell the DateFormat that you want the time in this timezone
df.setTimeZone(TimeZone.getTimeZone("America/Montreal"));
String whatIWant = df.format(date);

Categories

Resources