getTimeinMillis giving a negative value - java

This is my date
Thu Feb 20 18:34:00 GMT+5:30 2014
When I use getTimeInMillis() I'm geting a negative value(-5856679776000). It should be something positive. Can anyone tell me why?
The stored date i.e cal1 is giving a negative value while the second date i.e current date is a positive one.
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",java.util.Locale.getDefault());
try {
java.util.Date d = format.parse(date+" "+time);
GregorianCalendar cal1 = new GregorianCalendar(d.getYear(),
d.getMonth(),
d.getDay(),
d.getHours(),
d.getMinutes());
Calendar cal = Calendar.getInstance();
GregorianCalendar cal2 = new GregorianCalendar(cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH),
cal.get(Calendar.HOUR_OF_DAY),
cal.get(Calendar.MINUTE));
Toast.makeText(getApplicationContext(),
"Stored date " + d +
"\nCurrent date " + cal.getTime() +
"\nStored date in ms :" + cal1.getTimeInMillis() +
"\nCurrent time in ms :" + cal2.getTimeInMillis()+
"\nDifference " + ((cal1.getTimeInMillis()-cal2.getTimeInMillis())/1000),
Toast.LENGTH_LONG).show();
}
catch(Exception e) {
Toast.makeText(getApplicationContext(),"Date parsing error", Toast.LENGTH_LONG).show();
e.printStackTrace();
}

replace
new GregorianCalendar(d.getYear(), d.getMonth(), d.getDay(), d.getHours(), d.getMinutes());
with
new GregorianCalendar(1900+d.getYear(), d.getMonth(), d.getDay(), d.getHours(), d.getMinutes());
Check the documentation of getYear method. It returns years after 1900 ... And the second cause has been already identified by #Pakspul ..

You should swap cal1 and cal2 in your millisecond calculation. For example:
startdate = 12:00
enddate = 12:01
diff = enddate - startdate; // result is 1 minute
diff = startdate - enddate; // result is -1 minute

What you is doing here is that you are calling cal2 after cal1 so it will have definatly higher value than cal1 because it has the mostrecent time, hence the negative result value.
just switch them and try again like this:
Toast.makeText(getApplicationContext(),"Stored date "+d+"\nCurrent date "+cal.getTime()+"\nStored date in ms :"+cal1.getTimeInMillis()+"\nCurrent time in ms :"+cal2.getTimeInMillis()+"\nDifference "+((cal2.getTimeInMillis()-cal1.getTimeInMillis())/1000), Toast.LENGTH_LONG).show();
}

Related

Converting date from UTC to CET [duplicate]

This question already has answers here:
Convert Date/Time for given Timezone - java
(16 answers)
Closed 6 years ago.
I would like to convert a date given in the UTC format to a date in the CET format.
The problem is that I need to add or subtract hours accordingly.
Example:
Date = "2015-07-31 01:14:05"
I would like to convert it to German date (adding two hours):
2015-07-31 03:14:05"
My code:
private static Long convertDateFromUtcToCet(String publicationDate) {
//"2015-07-31 01:14:05"
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
//SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd");
Date date = null;
try {
date = simpleDateFormat.parse(publicationDate);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.setTime(date);
Date givenDate = calendar.getTime();
System.out.println("Original UTC date is: " + givenDate.toString());
TimeZone timeZone = TimeZone.getTimeZone("CET");
calendar.setTimeZone(timeZone);
Date currentDate = calendar.getTime();
System.out.println("CET date is: " + currentDate.toString());
long milliseconds = calendar.getTimeInMillis();
return milliseconds;
}
This prints:
Original UTC date is: Sat Jan 31 01:14:05 IST 2015
CET date is: Sat Jan 31 01:14:05 IST 2015
First of all, your pattern string is wrong. It's yyyy-MM-dd, not yyyy-mm-dd.
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
To parse with a given time zone, set it with:
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Try using:
long ts = System.currentTimeMillis();
Date localTime = new Date(ts);
String format = "yyyy-mm-dd hh:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(format);
// Convert Local Time to UTC (Works Fine)
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date gmtTime = new Date(sdf.format(localTime));
System.out.println("Local:" + localTime.toString() + "," + localTime.getTime() + " --> UTC time:"
+ gmtTime.toString() + "," + gmtTime.getTime());
// Convert UTC to Local Time
Date fromGmt = new Date(gmtTime.getTime() + TimeZone.getDefault().getOffset(localTime.getTime()));
System.out.println("UTC time:" + gmtTime.toString() + "," + gmtTime.getTime() + " --> Local:"
+ fromGmt.toString() + "-" + fromGmt.getTime());

To check time value in JSpinnerand set date in JDateChooser accordingly

I have two Jdatechooser(named as firstdate and lastdate) and Jspinner(named as starttime and endtime) in a gui.
The scenario is,
1.if i open gui i will get the current time and set it in endtime and currenttime-1 in starttime(the code is below),
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR, -1);
Date oneHourBack = cal.getTime();
String timeStamp = new SimpleDateFormat("HH:mm:ss").format(oneHourBack);
Date date = new SimpleDateFormat("HH:mm:ss").parse(timeStamp);
starttime.setValue(date);
2.For both the Jdatechooser i set the current date.
3.If current time is 00:44:36 (HH:mm:ss), in starttime(Jspinner) i have to set 23:44:36, with this i have to
set the firstdate(Jdatechooser) value to previous day date instead of current date.
for this am trying the following way,
Calendar currentTime = Calendar.getInstance();
Date curHr = currentTime.getTime();
String curtime = new SimpleDateFormat("HH").format(curHr);
int timeCheck = Integer.parseInt(curtime);
if(timeCheck > 00 && timeCheck < 01){
//code to set previous day's
date
}
is this the way to do it? or is there any better way available? Please help
You should be able to use the oneHourBack Date value as the value for the lastdate JDateChooser, as not only has the time been rolled back, but so has the date value, for example...
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 44);
cal.set(Calendar.SECOND, 36);
Date startTime = cal.getTime();
cal.add(Calendar.HOUR, -1);
Date endTime = cal.getTime();
System.out.println("startTime = " + startTime);
System.out.println("endTime = " + endTime);
Outputs...
startTime = Thu Feb 06 00:44:36 EST 2014
endTime = Wed Feb 05 23:44:36 EST 2014
This is the nice thing about Calendar

Calendar.getInstance(TimeZone.getTimeZone("UTC")) is not returning UTC time

I am really confused with the result I am getting with Calendar.getInstance(TimeZone.getTimeZone("UTC")) method call, it's returning IST time.
Here is the code I used
Calendar cal_Two = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println(cal_Two.getTime());
and the response I got is:
Sat Jan 25 15:44:18 IST 2014
So I tried changing the default TimeZone to UTC and then I checked, then it is working fine
Calendar cal_Two = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println(cal_Two.getTime());
TimeZone tz = TimeZone.getDefault() ;
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
Calendar cal_Three = Calendar.getInstance();
System.out.println(cal_Three.getTime());
TimeZone.setDefault(tz);
Result:
Sat Jan 25 16:09:11 IST 2014
Sat Jan 25 10:39:11 UTC 2014
Am I missing something here?
The System.out.println(cal_Two.getTime()) invocation returns a Date from getTime(). It is the Date which is getting converted to a string for println, and that conversion will use the default IST timezone in your case.
You'll need to explicitly use DateFormat.setTimeZone() to print the Date in the desired timezone.
EDIT: Courtesy of #Laurynas, consider this:
TimeZone timeZone = TimeZone.getTimeZone("UTC");
Calendar calendar = Calendar.getInstance(timeZone);
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("EE MMM dd HH:mm:ss zzz yyyy", Locale.US);
simpleDateFormat.setTimeZone(timeZone);
System.out.println("Time zone: " + timeZone.getID());
System.out.println("default time zone: " + TimeZone.getDefault().getID());
System.out.println();
System.out.println("UTC: " + simpleDateFormat.format(calendar.getTime()));
System.out.println("Default: " + calendar.getTime());
java.util.Date is independent of the timezone. When you print cal_Two though the Calendar instance has got its timezone set to UTC, cal_Two.getTime() would return a Date instance which does not have a timezone (and is always in the default timezone)
Calendar cal_Two = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println(cal_Two.getTime());
System.out.println(cal_Two.getTimeZone());
Output:
Sat Jan 25 16:40:28 IST 2014
sun.util.calendar.ZoneInfo[id="UTC",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
From the javadoc of TimeZone.setDefault()
Sets the TimeZone that is returned by the getDefault method. If zone
is null, reset the default to the value it had originally when the VM
first started.
Hence, moving your setDefault() before cal_Two is instantiated you would get the correct result.
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
Calendar cal_Two = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println(cal_Two.getTime());
Calendar cal_Three = Calendar.getInstance();
System.out.println(cal_Three.getTime());
Output:
Sat Jan 25 11:15:29 UTC 2014
Sat Jan 25 11:15:29 UTC 2014
You are definitely missing a small thing and that is you are not setting a default value:
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
So the code would look like:
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
Calendar cal_Two = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println(cal_Two.getTime());
Explanation: If you want to change the time zone, set the default time zone using TimeZone.setDefault()
Calendar currentTime = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
currentTime.set(Calendar.ZONE_OFFSET, TimeZone.getTimeZone("UTC").getRawOffset());
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, currentTime.get(Calendar.HOUR_OF_DAY));
calendar.getTimeInMillis()
is working for me
Following code is the simple example to change the timezone
public static void main(String[] args) {
//get time zone
TimeZone timeZone1 = TimeZone.getTimeZone("Asia/Colombo");
Calendar calendar = new GregorianCalendar();
//setting required timeZone
calendar.setTimeZone(timeZone1);
System.out.println("Time :" + calendar.get(Calendar.HOUR_OF_DAY)+":"+calendar.get(Calendar.MINUTE)+":"+calendar.get(Calendar.SECOND));
}
if you want see the list of timezones, here is the follwing code
public static void main(String[] args) {
String[] ids = TimeZone.getAvailableIDs();
for (String id : ids) {
System.out.println(displayTimeZone(TimeZone.getTimeZone(id)));
}
System.out.println("\nTotal TimeZone ID " + ids.length);
}
private static String displayTimeZone(TimeZone tz) {
long hours = TimeUnit.MILLISECONDS.toHours(tz.getRawOffset());
long minutes = TimeUnit.MILLISECONDS.toMinutes(tz.getRawOffset())
- TimeUnit.HOURS.toMinutes(hours);
// avoid -4:-30 issue
minutes = Math.abs(minutes);
String result = "";
if (hours > 0) {
result = String.format("(GMT+%d:%02d) %s", hours, minutes, tz.getID());
} else {
result = String.format("(GMT%d:%02d) %s", hours, minutes, tz.getID());
}
return result;
}
It is working for me.
Get in Timestamp type:
public static Timestamp getCurrentTimestamp() {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
final Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
Timestamp ts = new Timestamp(date.getTime());
return ts;
}
Get in String type:
public static String getCurrentTimestamp() {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
final Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
Timestamp ts = new Timestamp(date.getTime());
return ts.toString();
}
Try to use GMT instead of UTC. They refer to the same time zone, yet the name GMT is more common and might work.

Date/time conversion/arithmetic

I've below code in Java 1.7:
DateFormat df = DateFormat.getInstance();
Date startDate = df.parse("07/28/12 01:00 AM, PST");
The above date time (07/28/12 01:00 AM, PST) is in the properties file which is configurable. If this date time is already passed, then I need to get the current date, set the time part from above string which is 01:00 AM PST in the current date & if this time is also already passed, then get the next day & set the time part from above string in it. The final object should be Date since I need to use it in Timer object.
How can I do this efficiently? Should I convert from date to Calendar or vice-versa? Can any one provide snippet?
You should look into the Calendar class. You can use constructs like:
Calendar cal = Calendar.getInstance();
cal.setTime(startDate);
cal.add(Calendar.DAY_OF_YEAR, 1);
It also has methods for checking if your startDate is before() or after() a new date (use the current time).
While writing of the built-in Java date/time structure, i would be remiss if i didnt plug Joda Time, considered by many to be superior to the native Java implementation.
EDIT:
It would be more efficient to show an example of the Date.compareTo() process, as the Calendar.before() and Calendar.after() require comparisons against other Calendar objects, which can be expensive to create.
take a look at the following:
DateFormat df = DateFormat.getInstance();
Date startDate = df.parse("07/28/12 01:00 AM, PST");
Calendar cal = Calendar.getInstance();
cal.setTime(startDate);
Date now = new Date();
if (startDate.compareTo(now)< 0) {
System.out.println("start date: " + startDate + " is before " + now);
Calendar nowCal = Calendar.getInstance();
nowCal.add(Calendar.DAY_OF_YEAR,1);
cal.set(Calendar.DAY_OF_YEAR, nowCal.get(Calendar.DAY_OF_YEAR));
} else if (startDate.compareTo(now) == 0) {
System.out.println("startDate: " +startDate + " is equal to " + now);
} else {
System.out.println("startDate: " + cal + " is after " + now);
}
System.out.println(cal.getTime());
I think this should work...your algorthim has my head spinning a little and I'm in a different time zone, so you original string didn't work :P
try {
DateFormat df = DateFormat.getInstance();
Date startDate = df.parse("28/07/2012 01:00 AM");
System.out.println("StartDate = " + startDate);
Date callDate = startDate;
Calendar today = Calendar.getInstance();
Calendar start = Calendar.getInstance();
start.setTime(startDate);
System.out.println("Today = " + today.getTime());
// If this date time is already passed
// Tue Jul 31 12:18:09 EST 2012 is after Sat Jul 28 01:00:00 EST 2012
if (today.after(start)) {
//then I need to get the current date, set the time part from above string in the current date
Calendar timeMatch = Calendar.getInstance();
timeMatch.setTime(startDate);
timeMatch.set(Calendar.DATE, today.get(Calendar.DATE));
timeMatch.set(Calendar.MONTH, today.get(Calendar.MONTH));
timeMatch.set(Calendar.YEAR, today.get(Calendar.YEAR));
//& if this time is also already passed, then get the next day & set the time part from above string in it
if (timeMatch.after(today)) {
timeMatch.add(Calendar.DATE, 1);
}
callDate = timeMatch.getTime();
}
System.out.println("CallDate = " + callDate);
} catch (ParseException exp) {
exp.printStackTrace();
}
This produces the following output
StartDate = Sat Jul 28 01:00:00 EST 2012
Today = Tue Jul 31 12:18:09 EST 2012
CallDate = Tue Jul 31 01:00:00 EST 2012

Java.util.Calendar - milliseconds since Jan 1, 1970

Program followed by output. Someone please explain to me why 10,000,000 milliseconds from Jan 1, 1970 is November 31, 1969. Well, someone please explain what's wrong with my assumption that the first test should produce a time 10,000,000 milliseconds from Jan 1, 1970. Numbers smaller than 10,000,000 produce the same result.
public static void main(String[] args) {
String x = "10000000";
long l = new Long(x).longValue();
System.out.println("Long value: " + l);
Calendar c = new GregorianCalendar();
c.setTimeInMillis(l);
System.out.println("Calendar time in Millis: " + c.getTimeInMillis());
String origDate = c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH) + "-" + c.get(Calendar.DAY_OF_MONTH);
System.out.println("Date in YYYY-MM-DD format: " + origDate);
x = "1000000000000";
l = new Long(x).longValue();
System.out.println("\nLong value: " + l);
c.setTimeInMillis(l);
System.out.println("Calendar time in Millis: " + c.getTimeInMillis());
origDate = c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH) + "-" + c.get(Calendar.DAY_OF_MONTH);
System.out.println("Date in YYYY-MM-DD format: " + origDate);
}
Long value: 10000000
Calendar time in Millis: 10000000
Date in YYYY-MM-DD format: 1969-11-31
Long value: 1000000000000
Calendar time in Millis: 1000000000000
Date in YYYY-MM-DD format: 2001-8-8
The dates you print from Calendar are local to your timezone, whereas the epoch is defined to be midnight of 1970-01-01 in UTC. So if you live in a timezone west of UTC, then your date will show up as 1969-12-31, even though (in UTC) it's still 1970-01-01.
First, c.get(Calendar.MONTH) returns 0 for Jan, 1 for Feb, etc.
Second, use DateFormat to output dates.
Third, your problems are a great example of how awkward Java's Date API is. Use Joda Time API if you can. It will make your life somewhat easier.
Here's a better example of your code, which indicates the timezone:
public static void main(String[] args) {
final DateFormat dateFormat = SimpleDateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
long l = 10000000L;
System.out.println("Long value: " + l);
Calendar c = new GregorianCalendar();
c.setTimeInMillis(l);
System.out.println("Date: " + dateFormat.format(c.getTime()));
l = 1000000000000L;
System.out.println("\nLong value: " + l);
c.setTimeInMillis(l);
System.out.println("Date: " + dateFormat.format(c.getTime()));
}
Calendar#setTimeInMillis() sets the calendar's time to the number of milliseconds after Jan 1, 1970 GMT.
Calendar#get() returns the requested field adjusted for the calendar's timezone which, by default, is your machine's local timezone.
This should work as you expect if you specify "GMT" timezone when you construct the calendar:
Calendar c = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
Sadly, java.util.Date and java.util.Calendar were poorly designed leading to this sort of confusion.
Your timezone is most likely lagging behind GMT (e.g., GMT-5), therefore 10,000,000ms from epoch is December 31 1969 in your timezone, but since months are zero-based in java.util.Calendar your Calendar-to-text conversion is flawed and you get 1969-11-31 instead of the expected 1969-12-31.
You can figure out yourself if you change your first c.setTimeInMillis(l); in c.clear();

Categories