java difference between calendars - java

I'm just doing a simple difference of two timemilisseconds of two different calendar.
Example:
Calendar ini = Calendar.getInstance();
try {
Thread.sleep(1500);
} catch (InterruptedException e) {e.printStackTrace();}
Calendar end = Calendar.getInstance();
long diff = end.getTimeInMillis()-ini.getTimeInMillis();
System.out.println("diff "+diff);
System.out.println("ini date "+ ini.getTime());
System.out.println("end date "+ end.getTime());
System.out.println("diff time format "+timeFormat.format(diff));
The time format is:
private final static String TIME_STRING_FORMAT = "hh:mm:ss.SSS";
private static SimpleDateFormat timeFormat = new SimpleDateFormat(TIME_STRING_FORMAT);
And in the output, always appear 1 our of difference, is it problem of the SimpleDateFormat???
Output:
diff 1500
ini date Sun May 24 22:27:01 CEST 2015
end date Sun May 24 22:27:03 CEST 2015
diff time format 01:00:01.500
Thanks for your help!!

It looks like SimpleDateFormat uses a timezone. See this related question. So when you give it the time 1500 milliseconds, it thinks you're giving it the time since the beginning of epoch time in the GMT time. Then it translates this to your timezone, giving you some hours of offset. You probably want to set the timezone on your timeFormat to GMT. Try this:
Calendar ini = Calendar.getInstance();
try {
Thread.sleep(1500);
} catch (InterruptedException e) {e.printStackTrace();}
Calendar end = Calendar.getInstance();
long diff = end.getTimeInMillis()-ini.getTimeInMillis();
System.out.println("diff "+diff);
System.out.println("ini date "+ ini.getTime());
System.out.println("end date "+ end.getTime());
Date date = new Date(diff);
System.out.println(date);
timeFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("diff time format "+timeFormat.format(date));

The 1 hour difference is caused by your local time zone. Date(long) constructs a date a number of milli seconds after January 1st 1970 GMT. In continental Europe (during winter) 1500 milli seconds after the epoch is thus January 1st 01:00:01.500.
If you use Java 8 see the tutorial on Period and Duration. Duration is probably what you want to use.

Related

Wrong hours converted to epoch time

I'm trying to convert a date with epoch time method.
with these code below
long epoch = 0;
try {
epoch = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse("12/11/2017 23:20:23")
.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
It gives me the epoch time: 1513052423
Which once convert give: Tuesday 12 December 2017 04:20:23 and not 23:20:23 :/
According to documentation SimpleDateFormat is locale-sensitive. Please check or set your timezone
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));

Java convert data/time between timezone is inaccurate

TimeZone.setDefault(TimeZone.getTimeZone("Europe/Moscow"));
System.out.println("Default Timezone: " + TimeZone.getDefault());
String date = "08/04/2016 00:00:00";
SimpleDateFormat simpleDateFormatMoscow = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date moscowDt = simpleDateFormatMoscow.parse(date);
System.out.println("Moscow Date: " + simpleDateFormatMoscow.format(moscowDt));
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Bangkok"));
System.out.println("Bangkok Date: " + simpleDateFormat.format(moscowDt));
Calendar calendar = new GregorianCalendar();
calendar.setTime(moscowDt);
calendar.setTimeZone(TimeZone.getTimeZone("Asia/Bangkok"));
System.out.println("Bangkok Date: " + simpleDateFormat.format(calendar.getTime()));
System.out.println("Test Timezone");
System.out.println(TimeZone.getTimeZone("America/New_York"));
System.out.println(TimeZone.getTimeZone("Europe/Moscow"));
System.out.println(TimeZone.getTimeZone("Asia/Bangkok"));
I tried to use the code this snippet to convert date/time between Moscow and Bangkok. The result is as followed:
Default Timezone:
sun.util.calendar.ZoneInfo[id="Europe/Moscow",offset=14400000,dstSavings=0,useDaylight=false,transitions=78,lastRule=null]
Moscow Date: 08/04/2016 00:00:00
//util date/time
Bangkok Date: 08/04/2016 03:00:00
//joda time
Bangkok Date: 08/04/2016 03:00:00
However, when I convert date/time using https://singztechmusings.wordpress.com/2011/06/23/java-timezone-correctionconversion-with-daylight-savings-time-settings/ or google the time is
Moscow Date: 08/04/2016 00:00:00
Bangkok Date: 08/04/2016 04:00:00
Could anyone please tell me the correct way to convert data/time using java?
And Could anyone please tell me what I did wrong and why the result is inaccurate?
Your Java have wrong timezone offset: "offset=14400000" is 4 hours, but Moscow is UTC+3 for last year and a half.
Upgrade your java with tzupdater.
Java is using its own timezone data which is independenct from the host operation system. It might be inaccurate if you are not using the latest version of Java cause Russia (Europe/Moscow) has switched from daylight saving time to permanent standard time two years ago
This is one way to do it using your local time zone first.
public static void main(String[] args) {
// Create a calendar object and set it time based on the local time zone
Calendar localTime = Calendar.getInstance();
localTime.set(Calendar.HOUR, 17);
localTime.set(Calendar.MINUTE, 15);
localTime.set(Calendar.SECOND, 20);
int hour = localTime.get(Calendar.HOUR);
int minute = localTime.get(Calendar.MINUTE);
int second = localTime.get(Calendar.SECOND);
// Print the local time
System.out.printf("Local time : %02d:%02d:%02d\n", hour, minute, second);
// Create a calendar object for representing a Bangkok time zone. Then we set
//the time of the calendar with the value of the local time
Calendar BangkokTime = new GregorianCalendar(TimeZone.getTimeZone("Asia/Bangkok"));
BangkokTime.setTimeInMillis(localTime.getTimeInMillis());
hour = BangkokTime.get(Calendar.HOUR);
minute = BangkokTime.get(Calendar.MINUTE);
second = BangkokTime.get(Calendar.SECOND);
// Print the local time in Bangkok time zone
System.out.printf("Bangkok time: %02d:%02d:%02d\n", hour, minute, second);
//Then do the same for the Moscow time zone
Calendar MoscowTime = new GregorianCalendar(TimeZone.getTimeZone("Europe/Moscow"));
MoscowTime.setTimeInMillis(localTime.getTimeInMillis());
hour = MoscowTime.get(Calendar.HOUR);
minute = MoscowTime.get(Calendar.MINUTE);
second = MoscowTime.get(Calendar.SECOND);
// Print the local time in Moscow time zone
System.out.printf("Moscow time: %02d:%02d:%02d\n", hour, minute, second);
}

Calculating the time difference between two GMT time instances as String

I am trying to get time difference between dates as String format like 4 hours ago.
Here is my code
To my understanding Calendar.getInstance() gives time as GMT. my server time is GMT so the difference should be GMT Vs GMT however the difference with this code is GMT (Server) Vs. GMT +5 ( My Current timezone)
How can i make the difference GMT only?
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date convertedDate = new Date();
Calendar systemCal = Calendar.getInstance();
long currentTime = systemCal.getTimeInMillis();
/***********************************/
Calendar cal = Calendar.getInstance();
try {
convertedDate = dateFormat.parse(dateString);
} catch (Exception e) {
return "";
}
cal.setTime(convertedDate);
/***********************************/
CharSequence myDateString = DateUtils.getRelativeTimeSpanString(cal.getTimeInMillis(), currentTime, DateUtils.MINUTE_IN_MILLIS);
return myDateString.toString();
Try following codes. It demonstrates clearly on how to parse a String datetime to GMT timezone. Key point is the first line which sets the default timezone.
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
try {
Date convertedDate = dateFormatGmt.parse("2015-01-29 10:05:00");
long diffSeconds = (cal.getTimeInMillis() - convertedDate.getTime()) / 1000;
System.out.println("convertedDate: " + convertedDate);
System.out.println("current: " + cal.getTime());
System.out.println("Difference in seconds: " + diffSeconds);
}
catch (Exception e) {
e.printStackTrace();
}
The Calendar.getInstance() return the time zone the computer is set to. So unless you always have control over that i would advice using the getInstance(TimeZone zone) method.
http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#getInstance%28java.util.TimeZone%29
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
But if you want a easier way to do it i would advice to look in to joda time.
http://www.joda.org/joda-time/

Date to string is not correnct

Probably there will be simply and fast answer but I still cant find out why is the result of
Date date = new Date(60000); //one min.
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
String dateStr = dateFormat.format(date);
dateStr - 01:01:00
Still one hour more. Time zone? How can I set it without it? Thanks.
Date represents a specific moment in time, not a duration. new Date(60000) does not create "one minute". See the docs for that constructor:
Initializes this Date instance using the specified millisecond value. The value is the number of milliseconds since Jan. 1, 1970 GMT.
If you want "one minute from now" you'll probably want to use the Calendar class instead, specifically the add method.
Update:
DateUtils has some useful methods that you might find useful. If you want the elapsed time in HH:mm:ss format, you might try DateUtils.formatElapsedTime. Something like:
String dateStr = DateUtils.formatElapsedTime(60);
Note that the 60 is in seconds.
Three ways to use java.util.Date to specify one minute:
1. Using SimpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")) as shahtapa said:
Date date = new Date(60*1000); //one min.
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateStr = dateFormat.format(date);
System.out.println("Result = " + dateStr); //Result should be 00:01:00
2. Using java.util.Calendar as kabuko said:
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.MINUTE,1); //one min.
Date date = calendar.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
String dateStr = dateFormat.format(date);
System.out.println("Result = " + dateStr); //Result should be 00:01:00
Other calendar.set() statements can also be used:
calendar.set(Calendar.MILLISECOND,60*1000); //one min.
calendar.set(1970,0,1,0,1,0); //one min.
3. Using these setTimeZone and Calendar ideas and forcing Calendar to
UTC Time-Zone
as Simon Nickerson said:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.clear();
calendar.set(Calendar.MINUTE,1); //one min.
Date date = calendar.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateStr = dateFormat.format(date);
System.out.println("Result = " + dateStr); //Result should be 00:01:00
Note: I had a similar issue: Date 1970-01-01 was in my case -3 600 000 milliseconds (1 hour late) java.util.Date(70,0,1).getTime() -> -3600000
I recommend to use TimeUnit
"A TimeUnit represents time durations at a given unit of granularity and provides utility methods to convert across units, and to perform timing and delay operations in these units. A TimeUnit does not maintain time information, but only helps organize and use time representations that may be maintained separately across various contexts. A nanosecond is defined as one thousandth of a microsecond, a microsecond as one thousandth of a millisecond, a millisecond as one thousandth of a second, a minute as sixty seconds, an hour as sixty minutes, and a day as twenty four hours."
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/TimeUnit.html
Date date = new Date(); // getting actual date
date = new Date (d.getTime() + TimeUnit.MINUTES.toMillis(1)); // adding one minute to the date

computing time based on TimeZones

my code computes the date and time correctly including the dayLightSaving time,when run on my local server from india. But when I run the same code from US server I am getting the time which is one hour ahead for the timeZoneId which is not abserving DST.
TimeZone tz = TimeZone.getTimeZone("America/Phoenix");
Date currTime = getDateByTZ(new Date(), tz);
System.out.println("currTime" + currTime);
public static Date getDateByTZ(Date d, TimeZone tz) throws Exception {
if (tz == null) {
tz = TimeZone.getDefault();
}
Integer tzOffSet = tz.getRawOffset();
Integer tzDST = tz.getDSTSavings();
Integer defOffSet = TimeZone.getDefault().getRawOffset();
Integer defDST = TimeZone.getDefault().getDSTSavings();
Calendar cal = Calendar.getInstance(tz);
cal.setTime(d);
if (tz.inDaylightTime(d)) {
cal.add(Calendar.MILLISECOND, -defOffSet);
cal.add(Calendar.MILLISECOND, -defDST);
cal.add(Calendar.MILLISECOND, +tzOffSet);
cal.add(Calendar.MILLISECOND, +tzDST);
} else {
cal.add(Calendar.MILLISECOND, -defOffSet);
cal.add(Calendar.MILLISECOND, tzOffSet);
}
return cal.getTime();
}
Results from Localserver:
currTime:Mon Oct 22 01:52:21 IST 2012
Results from USserver:
currTime:Mon Oct 22 02:52:21 IST 2012
This code doesn't make much sense. A Date object doesn't have to be transformed to be used in another time zone. It represents a universal instant.
What makes sense is to use the time zone when displaying (or formatting as a string) a Date object. In this case, you should simply set the time zone on the DateFormat instance, and the universal instant that constitutes a date will be formatted in order to make sense for the given time zone.
Date now = new Date(); // now, whatever the timezone is
DateFormat df = DateFormat.getDateTimeInstance();
df.setTimeZone(TimeZone.getDefault());
System.out.println("Now displayed in the default time zone : " + df.format(now));
df.setTimeZone(TimeZone.getTimeZone("America/New_York"));
System.out.println("Now displayed in the New York time zone : " + df.format(now));

Categories

Resources