I am storing timezone value in database as +5:30 or +2:00 or -1:00
I am fetching data from database and changing time according to time zone in java.
Here I would like to know how can I get time according to saved timezone value.
Use Timezone and Calendar. And check SO before asking...
Examples here, or here
TimeZone tz = Calendar.getInstance().getTimeZone();
System.out.println(tz.getDisplayName());// (i.e. Moscow Standard Time)
System.out.println(tz.getID());
That should get the time zone that the computer the user is using has been set to.
Unless you want to use a complicated solution by pinging a server and making a server-side check to see where the IP came from, then that is the closest you're going to get.
Use SimpleDateFormat and setTimeZone
String timeZone = "GMT" + offset // offset is the value you store in the db( +5:30, -2:30)
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone(timeZone));
Date date = format.parse("2014-11-19T09:01:02");
Related
I am trying to query a mysql DATETIME from Java. I know the the time zone of the server, but I cannot pull the datetime out with the time zone as I would expect.
ResultSet rs = st.executeQuery(...);
Date d1=rs.getTime(i, Calendar.getInstance(TimeZone.getTimeZone("UTC")));
Date d2=rs.getTime(i, Calendar.getInstance(TimeZone.getTimeZone("PST")));
System.out.println("d1: "+d1.getTime());
System.out.println("d2: "+d2.getTime());
This leaves me with:
d1: 40258000
d2: 40258000
Am I missing something basic here?
ResultSet.getDate() does take the Calendar into account. But I cant use it because it truncates the time info. It's still strange ResultSet.getTime() wouldn't handle any timezone conversions.
The documentation states:
This method uses the given calendar to construct an appropriate millisecond value for the time if the underlying database does not store timezone information.
So perhaps the database does store time zone information in this case?
What does your value in the database look like, and what is it supposed to represent?
An alternative approach would be letting the MySQL server convert the time zone:
SELECT CONVERT_TZ(timefield,'PST','UTC') AS tf
for example would convert the DATETIME value in the field timefield from PST to UTC time (and then returning it as tf).
getTime on the Date class returns the epoch time according to http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Date.html
so it would adjust out your timezone. I think that page implies you should use the timezone adjusted calendar to get your local time.
i build a new website.but the host is in USA.i am not in USA.
i need get the time on the website page to compare with one local Variable.
But because of time difference,it has 8 hous difference。how to solve this problom?
my code
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
java.util.Date currentTime = new java.util.Date();
String dateString = formatter.format(currentTime); `
how to revise these code ?
java.util.Date does not support timezones. You should pass the TimeZone to the formatter instead, by calling formatter.setTimeZone(tz).
joda-time is considered a better choice when working with dates. Note that for the sake of formatting it is fine to use Date, but it is a general advise not to rely on it when it comes to i18n. (Note the many deprecated methods there)
Then make each user set his timezone. Ideally suggest / assume the timezone based on his browser locale. See here
And always store the dates in a fixed timezone - preferably GMT/UTC.
In order to handle timezones, Java includes the Olson timezone database. Find the city in the database that is in the same time zone as you are.
First, you need to get a TimeZone object for the timezone you want. Then, get a Calendar object with the current date and time (or the date and time you wish to use). You can format that with a SimpleDateFormat object.
TimeZone local = TimeZone.getTimeZone("Asia/Tokyo");
Calendar now = Calendar.getInstance(local); // gets time in the current timezone
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
formatter.setTimeZone(local)
String dateString = formatter.format(now.getTime());
Though if you're doing a lot of time manipulation, like Bozho says, go for joda-time. The Java date/time system is confusing and rather poorly designed.
In such cases I always change timezone in Linux:
mv /etc/localtime /etc/localtime-backup
ln -sf /usr/share/zoneinfo/Europe/Amsterdam /etc/localtime
It also can be helpful for reading log files for example (I always see my local time instead of calculating it each time when I need to dig into them)
I think you need to use a Calendar (they are more useful generally than just Date objects). If you create a Calendar, initialised with your locale and timezone, you can do calendar.setDate() using the date you created. If you create another Calendar object with the fields that were entered, you can then do comparisons between the two Calendar objects.
I have a mobile application where I capture a date/time and send it as miliseconds to a servlet. -For example I capture 12:55 AM in my cellphone and send it to my server-
So, I construct the date from the sent miliseconds and print it with SimpleDateFormat but the time is diferent, it prints 8:55 AM.
I know that the problem is because I use 2 diferent timezones, my question is:
how can I show that time without apply any timezone to show the same time?
Thanks in advance
You need to use Calendar to change the TimeZone but there is no API for that.
// Change a date in another timezone
public static Date changeTimeZone(Date date, TimeZone zone) {
Calendar first = Calendar.getInstance(zone);
first.setTimeInMillis(date.getTime());
Calendar output = Calendar.getInstance();
output.set(Calendar.YEAR, first.get(Calendar.YEAR));
output.set(Calendar.MONTH, first.get(Calendar.MONTH));
output.set(Calendar.DAY_OF_MONTH, first.get(Calendar.DAY_OF_MONTH));
output.set(Calendar.HOUR_OF_DAY, first.get(Calendar.HOUR_OF_DAY));
output.set(Calendar.MINUTE, first.get(Calendar.MINUTE));
output.set(Calendar.SECOND, first.get(Calendar.SECOND));
output.set(Calendar.MILLISECOND, first.get(Calendar.MILLISECOND));
return output.getTime();
}
Link: http://blog.vinodsingh.com/2009/03/date-and-timezone-in-java.html
I think this should work. I haven't extensively tested it.
Calendar and Date objects store their date information in milliseconds in relation to UTC.
(the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC)
This means that Calendar/Date Objects do not store different values for different Time Zones. They always use the same value internally... the format is what normally changes.
Maybe you can use a SimpleDateFormat in your local/default timezone:
SimpleDateFormat sdf = new SimpleDateFormat("S")
Date d = sdf.parse(milliseconds);
You can also try to change the DateFormat's timezone until it matches your expected output.
sdf.setTimeZone(TimeZone.getTimeZone("GMT-8"));
System.out.println(sdf.toString());
sdf.setTimeZone(TimeZone.getTimeZone("GMT-4"));
System.out.println(sdf.toString());
I am getting a date/time string from web in the format of "yyyy/mm/dd'T'HH:MM:SS'Z'" and it is in UTC.
Now I have to identify the current time zone of device and then convert this time to my local time..
How do I do it?
(FYI, Currently, UTC time is 10:25 AM, in India current time is 3:55 PM)
Try using TimeZone.getDefault() instead of TimeZone.getTimeZone("GMT")
From the docs:
... you get a TimeZone using
getDefault which creates a TimeZone
based on the time zone where the
program is running.
EDIT: You can parse date using SimpleDateFormat (there is also the documentation on the format string there). In your case, you want to do (untested):
// note that I modified the format string slightly
SimpleDateFormat fmt = new SimpleDateFormat("yyyy/MM/dd'T'HH:mm:ss'Z'");
// set the timezone to the original date string's timezone
fmt.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = fmt.parse("1998/12/21T13:29:31Z", new ParsePosition(0));
// then reset to the target date string's (local) timezone
fmt.setTimeZone(TimeZone.getDefault());
String localTime = fmt.format(date);
alternatively, use two separate instances of SimpleDateFormat, one for original and one for target time.
I need to store the timezone an email was sent from. Which is the best way to extract it from the email's 'Date:' header (an RFC822 date)? And what is the recommended format to store it in the database (I'm using hibernate)?
I recommend you use Mime4J.
The library is designed for parsing all kinds of email crap.
For parsing dates you would use its DateTimeParser.
int zone = new DateTimeParser(new StringReader("Fri, 27 Jul 2012 09:13:15 -0400")).zone();
After that I usually convert the datetimes to Joda's DateTime. Don't use SimpleDateFormatter as will not cover all the cases for RFC822.
Below will get you the Joda TimeZone (from the int zone above) which is superior to Java's TZ.
// Stupid hack in case the zone is not in [-+]zzzz format
final int hours;
final int minutes;
if (zone > 24 || zone < -24 ) {
hours = zone / 100;
minutes = minutes = Math.abs(zone % 100);
}
else {
hours = zone;
minutes = 0;
}
DateTimeZone.forOffsetHoursMinutes(hours, minutes);
Now the only issue is that the Time Zone you will get always be a numeric time zone which may still not be the correct time zone of the user sending the email (assuming the mail app sent the users TZ and not just UTC).
For example -0400 is not EDT (ie America/New_York) because it does not take Daylight savings into account.
Probably easiest to parse with JodaTime as it supports ISO8601 see Date and Time Parsing and Formatting in Java with Joda Time.
DateTimeFormatter parser2 = ISODateTimeFormat.dateTimeNoMillis();
System.out.println(parser2.parseDateTime(your_date_string));
Times must always be stored in UTC (GMT) with a timezone - i.e. after parsing convert from the timezone to GMT and remove daylight savings offset and save the original timezone.
You must store the date with the timezone after converting to UTC.
If you remove or don't handle the timezone it will cause problems when dealing with data that has come from a different timezone.
Extract the data from the header using some sort of substring or regular expression. Parse the date with a SimpleDateFormatter to create a Date object.
The timezone in the email will not show in which timezone it was send. Some programs use ever UTC or GMT. Of course the time zone is part of the date time value and must also be parse.
Why do you want know it.
- Do you want normalize the timestamp? Then use a DateFormat for parsing it.
- Do you want detect the timezome of the user that send the email? This will not correctly work.
It looks like you already mentioned this in one of your comments, but I think it's your best answer. The JavaMail library contains RFC822 Date header parsing code in javax.mail.internet.MailDateFormat. Unfortunately it doesn't expose the TimeZone parsing directly, so you will need to copy the necessary code directly from javax.mail.internet.MailDateParser, but it's worth taking advantage of the careful work already done.
As for storing it, the parser will give you the date as an offset, so you should be able to store it just fine as an int (letting Hibernate translate that to your database for you).