How can I get the current date and time in UTC or GMT in Java?
java.util.Date
has no specific time zone, although its value is most commonly thought of in relation to UTC. What makes you think it's in local time?
To be precise: the value within a java.util.Date
is the number of milliseconds since the Unix epoch, which occurred at midnight January 1st 1970, UTC. The same epoch could also be described in other time zones, but the traditional description is in terms of UTC. As it's a number of milliseconds since a fixed epoch, the value within java.util.Date
is the same around the world at any particular instant, regardless of local time zone.
I suspect the problem is that you're displaying it via an instance of Calendar which uses the local timezone, or possibly using Date.toString()
which also uses the local timezone, or a SimpleDateFormat
instance, which, by default, also uses local timezone.
If this isn't the problem, please post some sample code.
I would, however, recommend that you use Joda-Time anyway, which offers a much clearer API.
How to convert ZonedDateTime to Date?
You can convert ZonedDateTime to an instant, which you can use directly with Date.
Date.from(java.time.ZonedDateTime.now().toInstant());
Compare given date with today
strtotime($var);
Turns it into a time value
time() - strtotime($var);
Gives you the seconds since $var
if((time()-(60*60*24)) < strtotime($var))
Will check if $var
has been within the last day.
Comparing date part only without comparing time in JavaScript
I'm still learning JavaScript, and the only way that I've found which works for me to compare two dates without the time is to use the setHours
method of the Date object and set the hours, minutes, seconds and milliseconds to zero. Then compare the two dates.
For example,
date1 = new Date()
date2 = new Date(2011,8,20)
date2
will be set with hours, minutes, seconds and milliseconds to zero, but date1 will have them set to the time that date1 was created. To get rid of the hours, minutes, seconds and milliseconds on date1 do the following:
date1.setHours(0,0,0,0)
Now you can compare the two dates as DATES only without worrying about time elements.
Joda: convert the system date and time to date/time in another zone
A java.util.Date
doesn't have timezone information. Joda's DateTime
has, but it's wrapped into a Chronology
to translate this instant to "human readable" date/time fields.
But in the end, both objects just represent points (instants) in the time-line.
Just check the values of dateTime.getMillis()
, newDateTime.getMillis()
, dateTime.toDate().getTime()
and newDateTime.toDate().getTime()
. They will all be exactly the same, and this value represents the number of milliseconds since epoch (1970-01-01T00:00Z
).
The timezone passed to the DateTime
object just affects the output of toString()
(when this milliseconds value is "translated" to a local date and time), but it doesn't change the milliseconds value itself. So if you do:
DateTime dateTime = new DateTime(now, fromTimeZone);
System.out.println(dateTime);
It will print the date and time that's equivalent to the milliseconds value, but converted to the fromTimeZone
(America/New_York):
2017-08-22T13:33:08.345-04:00
The withZone
method just sets to a different timezone, but keeps the same milliseconds value:
DateTime newDateTime = dateTime.withZone(toTimeZone);
System.out.println(newDateTime);
The code above keeps the instant (the milliseconds value), but prints the equivalent date and time in the toTimeZone
(US/Central):
2017-08-22T12:33:08.345-05:00
The .toDate()
method returns a java.util.Date
, which just contains the same milliseconds value, and no timezone information. Then, System.out.println
implicity calls Date::toString()
method, and this converts the milliseconds value to the JVM's default timezone. In this case both will be:
Tue Aug 22 13:33:08 EDT 2017
Because both dates represent the same instant (the same number of milliseconds since epoch).
If you want to get a String
that contains the date in a specific format, you can use a org.joda.time.format.DateTimeFormatter
:
DateTimeFormatter fmt = DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss z yyyy").withLocale(Locale.ENGLISH);
System.out.println(fmt.print(new DateTime(DateTimeZone.forID("US/Central"))));
There's no need to convert dates objects, because actually no conversion is really happening: all methods above don't change the milliseconds value.
Also note that I used a java.util.Locale
to make sure the month and day of week are in English. If you don't specify a locale, the JVM default will be used, and it's not guaranteed to always be English (and it can also be changed, even at runtime, so it's better to always specify it).
Then I get the current date and set the timezone to be used when printing it. Note that you can get a DateTime
directly, there's no need to create a java.util.Date
.
The output will be:
Tue Aug 22 12:33:08 CDT 2017
To get exactly the same output you want (with both dates), you can do:
DateTimeFormatter fmt = DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss z yyyy").withLocale(Locale.ENGLISH);
DateTime nowNy = new DateTime(DateTimeZone.forID("America/New_York"));
DateTime nowCentral = nowNy.withZone(DateTimeZone.forID("US/Central"));
System.out.println(fmt.print(nowNy) + "--" + fmt.print(nowCentral));
The output will be:
Tue Aug 22 13:33:08 EDT 2017--Tue Aug 22 12:33:08 CDT 2017
Java new Date/Time API
Joda-Time is in maintainance mode and being replaced by the new APIs, so I don't recommend start a new project with it. Even in joda's website it says: "Note that Joda-Time is considered to be a largely “finished” project. No major enhancements are planned. If using Java SE 8, please migrate to java.time (JSR-310)." (if you don't want to or can't migrate from Joda to another API, you can desconsider this section).
If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.
If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).
The code below works for both.
The only difference is the package names (in Java 8 is java.time
and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp
), but the classes and methods names are the same.
The relevant classes are DateTimeFormatter
(to format the date to a String
in a specific format), ZonedDateTime
(which represents a date and time in a specific timezone) and a ZoneId
(which represents a timezone):
// formatter - use English locale for month and day of week
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
// current date/time in New York timezone
ZonedDateTime nowNy = ZonedDateTime.now(ZoneId.of("America/New_York"));
// convert to another timezone (US/Central)
ZonedDateTime nowCentral = nowNy.withZoneSameInstant(ZoneId.of("US/Central"));
// format dates
System.out.println(fmt.format(nowNy) + "--" + fmt.format(nowCentral));
The output is the same as above.
How to set time zone of a java.util.Date?
Use DateFormat. For example,
SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
isoFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = isoFormat.parse("2010-05-23T09:01:02");
Converting between java.time.LocalDateTime and java.util.Date
Short answer:
Date in = new Date();
LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault());
Date out = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());
Explanation:
(based on this question about LocalDate
)
Despite its name, java.util.Date
represents an instant on the time-line, not a "date". The actual data stored within the object is a long
count of milliseconds since 1970-01-01T00:00Z (midnight at the start of 1970 GMT/UTC).
The equivalent class to java.util.Date
in JSR-310 is Instant
, thus there are convenient methods to provide the conversion to and fro:
Date input = new Date();
Instant instant = input.toInstant();
Date output = Date.from(instant);
A java.util.Date
instance has no concept of time-zone. This might seem strange if you call toString()
on a java.util.Date
, because the toString
is relative to a time-zone. However that method actually uses Java's default time-zone on the fly to provide the string. The time-zone is not part of the actual state of java.util.Date
.
An Instant
also does not contain any information about the time-zone. Thus, to convert from an Instant
to a local date-time it is necessary to specify a time-zone. This might be the default zone - ZoneId.systemDefault()
- or it might be a time-zone that your application controls, such as a time-zone from user preferences. LocalDateTime
has a convenient factory method that takes both the instant and time-zone:
Date in = new Date();
LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault());
In reverse, the LocalDateTime
the time-zone is specified by calling the atZone(ZoneId)
method. The ZonedDateTime
can then be converted directly to an Instant
:
LocalDateTime ldt = ...
ZonedDateTime zdt = ldt.atZone(ZoneId.systemDefault());
Date output = Date.from(zdt.toInstant());
Note that the conversion from LocalDateTime
to ZonedDateTime
has the potential to introduce unexpected behaviour. This is because not every local date-time exists due to Daylight Saving Time. In autumn/fall, there is an overlap in the local time-line where the same local date-time occurs twice. In spring, there is a gap, where an hour disappears. See the Javadoc of atZone(ZoneId)
for more the definition of what the conversion will do.
Summary, if you round-trip a java.util.Date
to a LocalDateTime
and back to a java.util.Date
you may end up with a different instant due to Daylight Saving Time.
Additional info: There is another difference that will affect very old dates. java.util.Date
uses a calendar that changes at October 15, 1582, with dates before that using the Julian calendar instead of the Gregorian one. By contrast, java.time.*
uses the ISO calendar system (equivalent to the Gregorian) for all time. In most use cases, the ISO calendar system is what you want, but you may see odd effects when comparing dates before year 1582.
How to check if input date is equal to today's date?
A simple date comparison in pure JS should be sufficient:
// Create date from input value
var inputDate = new Date("11/21/2011");
// Get today's date
var todaysDate = new Date();
// call setHours to take the time out of the comparison
if(inputDate.setHours(0,0,0,0) == todaysDate.setHours(0,0,0,0)) {
// Date equals today's date
}
Here's a working JSFiddle.
Related Topics
Simple Ruby Input Validation Library
Strategies for Overriding Database.Yml
How to Split a String into Only Two Parts, by the Last Occurrence of the Split Char
Rails: How to Get a File Extension/Postfix Based on the Mime Type
How Does Pack() and Unpack() Work in Ruby
How to Convert a Ruby String Range to a Range Object
Most Efficient Way to Calculate Hamming Distance in Ruby
Why Can't I Install SASS on MAC Os Sierra
How to Append Data to JSON in Ruby/Rails
Error Occurred While Installing Mini_Racer (0.2.0)
Sinatra Static Assets Are Not Found When Using Rackup
How to Access Class Variables in Ruby 1.9
If Else Statements in .Html.Erb in Views
<Rubygems> How to Change Gem Environment Settings
How Does MACports Install Packages? How to Activate a Ruby Installation Done via MACports
Clarification on the Ruby << Operator
Convert Array to Hash While Preserving Array Index Values in Ruby