In this code
long timestamp=1332782463298;
Date d=new Date(timestamp);
date=d.toLocaleString();
date is always current date. Where is my mistake?
I've also tried SimpleDateFormat, but it still returns current date:
date=new SimpleDateFormat("MM.dd.yyyy").format(d);
That timestamp is for March 26th 2012 (17:21:03.298 UTC, to be precise). Try a suitably different timestamp (e.g. 1332482563298L) and you'll get a different date...
Note that you shouldn't really be using toLocaleString anyway - SimpleDateFormat is the way to go (or Joda Time if possible). You might also want to consider which time zone you're interested in.
I'm sorry, but do you understand what long timestamp=1332782463298; is ? It's a UNIX time stamp in milliseconds since 1 January 1970, if you keep it same, date will contains same time all the time.
Use Calendar instead:
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(1332782463298);
Date d = cal.getTime();
String current = SimpleDateFormat("MM.dd.yyyy").format(cal.getTime()).toString();
Related
How can I get UTC DateTime from the following code? Right now with these lines of code, I get an output like this Fri Dec 31 05:30:00 IST 9999. Is this output is correct? I mean to say is this time is the UTC time. Any suggestions or help?
Code snapshot
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.set(9999, 11, 31, 0, 0, 0);
Date date = cal.getTime();
System.out.println(date);
Well, the output is correct in that it's what I'd expect for midnight UTC when you're running on a system in IST. Date.toString() always uses your system local time zone - because it doesn't have any other information. A Calendar knows its time zone, but a Date doesn't. The underlying information is just "the number of milliseconds since the Unix epoch".
If you want to convert a Date to a textual representation in a particular time zone, use SimpleDateFormat and specify the time zone there.
The problem here is that you're using the Date.toString() method that returns the local time zone.
You can use this code to get the current time in UTC:
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
And then just use that object to get the time you want and use it, do note that cal.getTimeInMillis() or getTime() both return the time from the Epoch that is set to January 1, 1970 00:00:00.000 GMT (Gregorian). So if you want to print the time or use it for something other then calculate the difference in time you can use, for example:
System.out.println(cal.get(Calendar.YEAR));
However if you want to get the difference of time between this time and another you should create another calendar instance for that other time (because of the way getTimeInMillis() work). So you can just do something like:
Calendar time = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
time.set(Calendar.YEAR, year);
time.set(Calendar.MONTH, month);
time.set(Calendar.DAY_OF_MONTH, day_of_month);
time.set(Calendar.HOUR_OF_DAY, hour_of_day);
time.set(Calendar.MINUTE, minute);
time.set(Calendar.SECOND, second);
long difInMillis = cal.getTimeInMillis() - time.getTimeInMillis();
Also you should always remember that the month starts from 0 and not from 1, to be sure you can use Calendar.[your_month_here] and check the values.
You can find more information here: http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html
In my app, I am using SimpleDateFormat to convert the Date object to a string. But sometime when I change the time zone one by one to test whether the date I enter is the same as the date converted to a string, I found that it shows a different date. For example, suppose I have Thu Mar 15 00:00:00 GMT+08:00 2012 in my Date object, Now when I convert it to a string using SimpleDateFormat it works fine, but when I change the time zone one by one and check whether the date converted to string is same as it stored in Date object then in some cases it shows as 14-Mar-2012 instead of showing 15-Mar-2012. Why this happen? Can anyone please suggest me how to solve this out?
Code I have used:
SimpleDateFormat m_sdFormatter = new SimpleDateFormat("dd-MMM-yyyy");
String selected_date = m_sdFormatter.format(btnSelectedDt.getTime());
try this ,hope it may help you..
private String getDate(long timeStamp) {
DateFormat objFormatter = new SimpleDateFormat("dd-MM-yyyy");
objFormatter.setTimeZone(TimeZone.getDefault());
Calendar objCalendar = Calendar.getInstance(TimeZone.getDefault());
objCalendar.setTimeInMillis(timeStamp * 1000);
String result = objFormatter.format(objCalendar.getTime());
objCalendar.clear();
return result;
}
For example suppose i have Thu Mar 15 00:00:00 GMT+08:00 2012 in my Date object,
You haven't got that (even though that's no doubt what toString displays). A Date object doesn't contain a time zone. It contains an instant in time, which can be interpreted as different dates and times based on the calendar and time zone you use to interpret it. So that's midnight in once specific time zone - but the Date object itself is just a number of milliseconds since the unix epoch.
It's not clear exactly what you're doing, but you shouldn't be surprised that changing the time zone used in SimpleDateFormat will change the date written out. If you can describe in more detail what the larger goal is, we may be able to help you more. Note that if you can use Joda Time instead, that's a much better date/time API - but I know that it's quite large for use in an Android app.
In your SimpleDateFormat, mention the locale,
DateFormat objFormatter = new SimpleDateFormat("dd-MM-yyyy", locale);
where locale is of your choice. For eg, I use Locale.ENGLISH as it contains the date format that I require. Otherwise when you change ure locale in the device, the simpledateformat changes to current locale and you end up getting the wrong date.
I'm trying to take a Date and update it based on another timezome and I've written this code below. I noticed then I set the new time zone which is CST a call to getHour reflects the update but when getTime() the date does not reflect the time based on the timezone last set.
TimeZone zone = TimeZone.getTimeZone(TimeZoneConstants.AmericaNewYork);
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(TimeZoneConstants.AmericaNewYork));
System.out.println(cal.get(Calendar.HOUR_OF_DAY));
System.out.println(DateHelper.formatDate(cal.getTime(), DateHelper.FORMAT_TIME_LONG));
Calendar cal2 = Calendar.getInstance();
TimeZone zone2 = cal2.getTimeZone();
cal.setTimeZone(zone2);
System.out.println(cal.get(Calendar.HOUR_OF_DAY));
System.out.println(DateHelper.formatDate(cal.getTime(), DateHelper.FORMAT_TIME_LONG));
output
16
3:14:36 PM CST
15
3:14:36 PM CST
From this the console output is below as you can see the hour is updated but the Date object returned from getTime() is not. I can write a uitl method to get what I want but am wondering why this happens by defauit? - Duncan Krebs
You never changed the time, in terms of raw milliseconds since epoch, at all. Changing the timezone just changes the 'human' representation. 3:14pm Central and 4:14pm Eastern are exactly the same when represented by a java.util.Date. They're both the same amount of raw time since epoch. If you want the human readable representation to be in Eastern time, you need to tell that to the DateHelper doing the formatting.
I know there are other similar questions to this, but I came up with my own way of getting the current time in a specific time zone, so I just wanted to confirm if it is correct or not, or there are gotchas I didn't take care of.
Calendar cal = Calendar.getInstance();
// Assuming we want to get the current time in GMT.
TimeZone tz = TimeZone.getTimeZone("GMT");
cal.setTimeInMillis(calendar.getTimeInMillis()
+ tz.getOffset(calendar.getTimeInMillis())
- TimeZone.getDefault().getOffset(calendar.getTimeInMillis()));
// Calendar should now be in GMT.
Is the above correct at all? I did my own test and it seemed to be working as expected, but just wanted to confirm it again with the experts in Stack Overflow.
If you simply do a Calendar.getInstance with the TimeZone argument, the calendar's internal state for the get() methods will return you the field with the time for that timezone. For example:
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
// if i run this at 9 EST this will print 2
System.out.println(cal.get(Calendar.HOUR));
If you just need the local time for display purposes, you can set the TimeZone on your format object. For example:
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss z");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(sdf.format(new Date()));
Like Macarse said though, Joda time is where it's at if you need to do anything more complex. The Java date APIs are a nightmare.
I'd prefer using joda-time instead of that.
Check this link.
My server has GMT+7, so if i move to another server has another GMT timezone, all date stored in db will incorrect?
Yes Q1 is correct, how about i will store date in GMT+0 timezone and display it in custom GMT timezone chosen by each member
How i get date with GMT+0 in java
1) To quote from the javadocs, Java millisecond timestamps are
the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.
Therefore, as the timestamp is UTC/GMT, if you store it in the database this date will be correct no matter the time zone of the server.
2) Formatting the timestamp for display depending on the timezone would be the correct approach.
3) Creating a new java.util.Date instance and calling getTime() will get you the timestamp for GMT+0 in Java.
To add to mark's point, once you have a java.util.Date, you can "convert" it to any Timezone (as chosen by the User). Here's a code sample in Groovy (will work in Java with slight mods):
// This is a test to prove that in Java, you can create ONE java.util.Date
// and easily re-display it in different TimeZones
fmtStr = "MM/dd/yyyy hh:mm aa zzz"
myDate = new java.util.Date()
sdf = new java.text.SimpleDateFormat(fmtStr)
// Default TimeZone
println "Date formatted with default TimeZone: " + sdf.format(myDate)
// GMT
sdf.setTimeZone(TimeZone.getTimeZone("GMT"))
println "Date formatted with GMT TimeZone: " + sdf.format(myDate)
// America/New_York
sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"))
println "Date formatted with America/New_York TimeZone: " + sdf.format(myDate)
// PST
sdf.setTimeZone(TimeZone.getTimeZone("PST"))
println "Date formatted with PST TimeZone: " + sdf.format(myDate)
By default when you get a date in java its in your current timezone, you can use the TimeZone class to get the timezone your system time is running in. Most databases supports that dates can be stored WITH timezone, which probably would be the right way to do this, but exactly what the format is can be dependant on which database you use.
I would suggest that you use Date only as a "holder" and propose that you use Calendar instances instead. To get a Calendar in the GMT time zone just use this:
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+00"))
A Calendar will provide a great deal of benefit when you work with times and dates. For instance, adding an hour to this is simple:
cal.add(Calendar.HOUR, 1);
Lastly, when you need a Date you just use this:
Date date = cal.getTime();
For Q3, consider using ZonedDateTime class.