This question already has answers here:
How to convert date time from one time zone to another time zone
(5 answers)
Closed 7 years ago.
There is the date date1 given with the format YY-MM-dd hh:mm:ss.SSS
I want to compare
date1.getTime()
with one retrieved by doing
new Date().getTime()
There is
SimpleDateFormat sf = new SimpleDateFormat("YY-MM-dd hh:mm:ss.SSS");
Date date1 = sf.parse(date1AsString);
...
compare date1.getTime() with new Date().getTime();
How can I bring these two dates to a common 'timezone' to compare them?
How can I obtain date1 to be on the same 'time length' as new Date()? I want to have the same timezone...
Thanks
From the javadoc of Date
The class Date represents a specific instant in time, with millisecond precision.
An instance in time is agnostic of our definition of time enhanced with time zones. Right now is the same for you and me, regardless of the fact that we are (potentially) in different time zones.
What adds the notion of a time zone is the DateFormat
The date is represented as a Date object or as the milliseconds since January 1, 1970, 00:00:00 GMT.
When you invoke Date#getTime(), you get back
the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
This is something you can use to compare Date objects since they have the same root. Similarly, the compareTo will return
the value 0 if the argument Date is equal to this Date; a value
less than 0 if this Date is before the Date argument; and a value
greater than 0 if this Date is after the Date argument.
You cannot compare two dates if their timezone information is unknown.
For example if your date1AsString variable is simply 2014-12-16 16:00:00 then you cannot tell if it is greater than or less than 2014-12-16 20:00:00+0000.
It looks like first date is 4 hours less than second one; but if someone adds that the first date is Pacific Time (UTC-0800) then it would actually be 4 hours more than the second date (2014-12-16 16:00:00-0800 = 2014-12-17 00:00:00+0000).
So, if date1AsString has an unknown timezone then you cannot convert it to UTC or anything else for comparison.
getTime() Returns the number of milliseconds since January 1, 1970, 00:00 :00. You will want to compare the two longs, roughly like so:
long time = new Date().getTime();
long time2 = date1.getTime();
if(time>time2)
System.out.println(String.format("time is greater than time2 by %d", time-time2)
else
System.out.println(String.format("time2 is greater than time by %d", time2-time)
if you know Timezone
date1.setTime(date1.getTime()+/-(3600000*hours)) to convert, if date1 time is GMT to go to GMT+2 hours must be 2 and sing must be +
Typically any server environment is going to be using GMT so you wont have to worry about the timezone when comparing dates, only when formatting the value to be display to users.
You can compare two dates like so:
SimpleDateFormat sf = new SimpleDateFormat("YY-MM-dd hh:mm:ss.SSS");
Date date1 = sf.parse(date1AsString);
boolean isBefore = date1.before(new Date());
boolean isAfter = date1.after(new Date());
Alternatively, you can compare the numeric values of the unix time to get the same result:
...
boolean isBefore = date1.getTime() < new Date().getTime();
boolean isAfter = date1.getTime() > new Date().getTime();
The Date Class has methods like before(date) and after(date). You should take a look into the Date Class.
So I think what you are looking for is to set the time zone of the SimpleDateFormat:
sf.setTimeZone(TimeZone.getTimeZone("EST"));
Related
This question already has answers here:
Calendar returns date in wrong time zone
(5 answers)
Closed 3 years ago.
I am trying to convert my datetime that is in local timezone into UTC date time.
Date localDate; // this is local date
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ") ;
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateStr = simpleDateFormat.format(localDate);
i am getting proper converted UTC time in dateStr now i want to convert it into Date object with UTC timezone only
but the moment i do that i am again getting the localDate.
//converting string to date object
simpleDateFormat.parse(dateStr)
does anyone know how can i convert local date object to UTC date object
here is the value i am getting while debugging
here dateStr is showing proper date in UTC but utcDate object is showing the local time
Date class is intended to reflect coordinated universal time (UTC) time. It can be formatted into ANY form you want, e.g. you can format it into your local time zone or UTC time zone.
See from javadoc: https://docs.oracle.com/javase/8/docs/api/java/util/Date.html
Although the Date class is intended to reflect coordinated universal time (UTC), it may not do so exactly, depending on the host environment of the Java Virtual Machine. Nearly all modern operating systems assume that 1 day = 24 × 60 × 60 = 86400 seconds in all cases. In UTC, however, about once every year or two there is an extra second, called a "leap second." The leap second is always added as the last second of the day, and always on December 31 or June 30. For example, the last minute of the year 1995 was 61 seconds long, thanks to an added leap second. Most computer clocks are not accurate enough to be able to reflect the leap-second distinction.
In my program I need to read a Time value from the database and then convert that value to milliseconds.
I do it like this :
Time t = getTimeFromDatabase();
long millis = t.getTime();
The problem is that the value of millis corresponds to time value which is 1 hour earlier than what is entered in the database.
For example: let's say that the value in the DB is 09:30:00. So if I do this:
Time t = getTimeFromDatabase();
System.out.println(t.toString);
System.out.println(t.getTime);
Output would be:
09:30:00
30600000
Now... 09:30:00 is ok. That's how it is in the DB.
But 30600000 / 3600000 = 8.5 (3600000 is milliseconds per hour). Which means that this value in milliseconds corresponds to 08:30:00.
The correct value for 09:30:00 should be 34200000.
My question is how can I get correct value regardless of time zone (I am in UTC +1, so I guess that this has something to do with my problem).
I have tried with other time values but it is always the same (1 hour earlier).
Thanks in advance.
When you parse the data from DB into a Time object, you should use a formatter, and set the proper time zone.
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
timeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = timeFormat.parse(dataFromDB); // dataFromDB is a "09:30:10" like String
System.out.println(timeFormat.format(date)); // will print time in HH:mm:ss format
System.out.println(date.getTime()); // will print milliseconds
I am trying to get the the day and time in UTC as milliseconds but repeatedly get the same problem. The result should be something like '63530139420000' but each time the value '1394547490884' is returned.
To get the date and time in UTC I use the following method:
long dateutc = System.currentTimeMillis();
Can anyone tell me what is the problem?
You can use this.
DateFormat df = DateFormat.getTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateutc = df.format(new Date());
Your code correctly gets the number of milliseconds since January 1, 1970 00:00:00 UTC.
Interestingly if you take the value your teacher has specified and divide by the number of milliseconds in a year you get 2014.5. So either your teacher doesn't know what currentTimeMillis() does or he wants milliseconds since year 0 (which doesn't make any sense to me).
To calculate number of milliseconds since a given date all you need to do is to create two date instances and subtract the milliseconds values from getTime().
My requirment is like this:
I am saving time in millisecond in database and the timezone.For example the time in milisecond is 1223123123232 in long and timezone is Asia/Calcutta. I have to convert it to Africa/Asmara timezone.
long l = 1223123123232l;
TimeZone tz = TimeZone.getTimeZone("Asia/Calcutta");
long tzOff = tz.getOffset(l);
java.util.Date d = new Date(l-tzOff); // WHY THIS??
DateFormat df = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");
df.setTimeZone(TimeZone.getTimeZone("Africa/Asmara"));// required timezone
String s = df.format(d);
System.out.println(s);
To check i am refering this: link
My question is:
If the timezone is just the representation of time in different formats(geographical areas offset from GMT),why do i need to subtract the offset time form the actual time (l-tzOff)?
Why can't i ignore the timezone which is saved in Database, and only consider the timezome in which i want to convert the date?
Something like:
long l = 1223123123232l;
java.util.Date d = new Date(l);
DateFormat df = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");
df.setTimeZone(TimeZone.getTimeZone("Africa/Asmara"));// required timezone
String s = df.format(d);
System.out.println(s);
My system timezone is Asia/Calcutta, i want to convert a Date in Africa/Bujumbura timezone to Europe/Vatican timezone.The above code is not working in this case? Why this is so?
Java dates do not know about time zones. Therefore, if I save 14H00 in New-York, it will not be the same 14H00 as in Paris, although the millisecond value is the same. You need to use a unique reference to save dates. People often chose GMT+0.
If you need to check local time across timezones, you can use a tool I developed here.
To answer your questions:
Timezone is not a representation of time, it is a localisation of time. The reason you would substract an offset is to make sure all time is defined according to the same reference.
Because you would get false results and false dates.
new Date(long) takes the number of milliseconds since the GMT epoch. Since in your case l is the number of milliseconds since some other point in time (namely 1 Jan 1970, 00:00:00 in Asia/Calcutta), you have to convert it to GMT first. This is done by subtracting the relevant timezone offset.
I have this code:
Date now = new Date();
// the string is in UTC format, so a UTC date must be constructed, I don't know if that happens in this format
Date measure = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(utcDateTime);
long diff = now.getTime() - measure.getTime();
if (diff < 1000* 60 * 15) {
// measure is less then 15 minutes recent
do some work
}
When I get the diff, it includes the timezone. I know the Date object internally is UTC.
So what's wrong here?
While a Date object is indeed in UTC, your SimpleDateFormat may not be. I suspect it default's to the system time zone - that's certainly what experimentation would suggest. You can change this using DateFormat.setTimeZone. So if your text represents a UTC date/time, you should set the time zone of the formatter to UTC as well.
Or you could use Joda Time, which is a generally better date and time API :)