I have a method as follows:
public void storeAppointment(int year,
int monthOfYear,
int dayOfMonth,
int hourOfDayFrom,
int minuteFrom,
int hourOfDayUntil, int minuteUntil) {
Calendar appointmentCalendar = Calendar.getInstance();
appointmentCalendar.set(year, monthOfYear, dayOfMonth);
TimeZone tz = appointmentCalendar.getTimeZone();
DateTimeZone jodaTz = DateTimeZone.forID(tz.getID());
DateTime appointmentDateTime = new DateTime(appointmentCalendar.getTimeInMillis(), jodaTz);
LocalDate localDate = appointmentDateTime.toLocalDate();
// At this point I have the appointment date.
// Should e.g. throw an exception for invalid time interval
validate(hourOfDayFrom, minuteFrom, hourOfDayUntil, minuteUntil);
// set proper times for calendar
appointmentCalendar.set(Calendar.HOUR, hourOfDay);
appointmentCalendar.set(Calendar.MINUTE, minute);
// store date and times
// Should I update the localDate instead of the appointmentCalendar?
}
Questions:
How should I validate the hours/minutes? Should the actual date be included or is that not relevant?
Should I update the localDate instead of the appointmentCalendar?
You are working much too hard here.
Avoid legacy date-time classes
Avoid using the troublesome old date-time classes, such as Date & Calendar. Now legacy, supplanted by the java.time classes.
Do not mix date-time libraries
Do not mix the different date-time libraries. If using Joda-Time, no need for java.util.Date and no need for java.util.Calendar. And if using java.time classes, no need for Joda-Time and no need for java.util.Date/.Calendar.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
Business rules
Should the actual date be included or is that not relevant?
We cannot tell you whether to consider the date or not. That depends on your business rules.
For example, if your business always takes a lunch break from noon to 13:00, then any business record marked with a time-of-day in that hour must be invalid. Date is irrelevant here if you always take the same lunch break every single day.
But if your scenario is something like recording a worker’s periods worked, then no two periods should overlap on the same day. In this case you must consider the date.
ZonedDateTime
Should I update the localDate instead of the appointmentCalendar?
a) You should not be mixing these classes, as discussed above.
b) In both Joda-Time and java.time, the LocalDate class represents a date-only value without time-of-day. And like its sibling Local… classes, it purposely has no concept of time zone. So not at all a fit for your purpose.
You need to use ZonedDateTime to represent a date and a time-of-day that has meaning within your intended time zone.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate ld = LocalDate.of( 2016 , 1 , 23 );
LocalTime lt = LocalTime.of( 12 , 30 );
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z );
To get the current moment:
Instant instant = Instant.now(); // UTC.
ZonedDateTime zdt = instant.atZone( z );
…or, as a shortcut…
ZonedDateTime zdt = ZonedDateTime.now( z );
Also, the java.time classes are immutable objects. So you do not change (“mutate”) their values. Instead you instantiate a new object based on the original’s values.
Interval
You may find the Interval class in ThreeTen-Extras project to be helpful here.
Interval a = Interval.of( zdtStart.toInstant() , zdtStop.toInstant() );
You can compare intervals with methods such as contains, overlaps, encloses, isBefore, and isAfter.
Boolean overlaps = a.overlaps( b );
Pass around objects
Rather than pass around mere primitives of piecemeal data, pass objects.
So instead of passing primitives such as integers for month, date, and hour, pass java.time objects such as Instant, OffsetDateTime, ZonedDateTime. When you have only the date or only the time-of-day, pass LocalDate or LocalTime.
Default time zone
To get the JVM’s current default time zone, call ZoneId.systemDefault.
But if important you should be asking the user for their desired/expected time zone. That default can change at any moment by any code in any thread of any app running in that JVM.
Related
I'm creating a string out from current time and I wanted to convert it to timestamp again, but the thing is, that it's subtracts 2 hours while converting.
This is the steps I'm doing -
DateTimeFormatterBuilder dateTimeFormatterBuilder = new DateTimeFormatterBuilder().append(DateTimeFormatter.ofPattern("uuuu-MM-dd")).appendLiteral(" ")
.append(DateTimeFormatter.ofPattern("HH:mm:ss")).parseLenient();
long ts = Clock.systemUTC().millis();
System.out.println(ts);
Instant instant = Instant.ofEpochMilli(ts);
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, ZoneOffset.UTC);
String str = zonedDateTime.format(dateTimeFormatterBuilder.toFormatter());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
long timestamp = simpleDateFormat.parse(str).getTime();
System.out.println(timestamp);
} catch (ParseException e) {
e.printStackTrace();
}
output -
1639065502667
1639058302000
(2021-12-09 15:58:22
2021-12-09 13:58:22)
why is the diff of the 2 hours?
how can I parse it so that the outputs will be equal?
tl;dr
Trying to understand Date, Calendar, and SimpleDateFormat is a huge waste of time. Use only their replacements, the java.time classes.
LocalDateTime // Represent a date with time-of-day, but lacking the context of a time zone or offset-from-UTC. So *not* a moment, *not* a point on the timeline.
.parse( // Parse your text string input into a date-time object.
"2021-12-09 15:58:22" // Your input of date with time-of-day but no offset/zone.
.replace( " " , "T" ) // Replace SPACE with a `T` to comply with standard ISO 8601 format.
) // Returns a `LocalDateTime` object.
.atZone( // Place that date-with-time into the context a particular time zone.
ZoneId.of( "America/Montreal" ) // Specify a time zone by its `Continent/Region` name.
) // Returns a `ZonedDateTime` object, a date with time-of-day as seen through the wall-clock time used by the people of a particular region. This *does* represent a moment, *is* a specific point on the timeline.
.toInstant() // Adjust from time zone to UTC (an offset of zero hours-minutes-seconds). This represents the very same moment as the `ZonedDateTime` object above, but as seen through a different wall-clock time.
.toEpochMilli() // Get a count of milliseconds from first moment of 1970 in UTC (1970-01-01T00:00Z) to the moment of our `Instant` object (& `ZonedDateTime` object).
See this code run live at IdeOne.com. There you can click fork to make a copy, alter, and run.
1639083502000
Avoid legacy date-time classes
Regarding your specific question about a two hour difference, the obvious cause would be a time zone difference.
Parsing incomplete information
Your parsing, SimpleDateFormat("yyyy-MM-dd HH:mm:ss") is something of a wild card. The result will be a java.util.Date object, which represents a moment, a date with time-of-day as seen with an offset of zero. But your input lacks an indicator of offset or zone. As commented by Sotirios Delimanolis, you are parsing with partial input, with incomplete information.
So some default zone/offset will be applied. I do not know what zone or offset in particular, because I do not care. That terrible class is tragically flawed, and should be avoided.
Also, yet another problem with the Date class is that its toString method has the anti-feature of applying the JVM’s current default time zone to adjust away from the UTC value represented by that class. Very confusing, as this creates the illusion of that zone being a part of Date object but it is not. As I said, a terrible class, tragically flawed.
Use only java.time classes instead.
java.time
Understand that a date with time-of-day is inherently ambiguous, is not a moment.
If you are tracking 4 PM on the 9th, we do not know if that means 4 PM in Tokyo Japan, 4 PM in Toulouse France, or 4 PM in Toledo Ohio US — three very different moments that happen several hours apart.
LocalDateTime ldt = LocalDateTime.parse( "2021-12-09 16:00:00" ) ;
To track a moment, a point on the timeline, you must place ne date-with-time in the context of an offset from UTC or of a time zone.
An offset is merely a number of hours-minutes-seconds ahead or behind the baseline of modern timekeeping, the prime meridian at Royal Observatory, Greenwich.
A time zone is much more. A time zone is a named history of the past, present, and future changes to the offset used by the people of a particular region. Each zone has a name in format of Continent/Region such as Europe/Berlin or Asia/Tokyo.
To track moments as seen in UTC, with an offset of zero, use Instant.
Instant instant = Instant.now() ;
To see that same moment through the wall-clock time used by people in a region, apply a ZoneId to get a ZonedDateTime.
ZoneId z = ZoneId.of( "America/Edmonton" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
As for your use of SimpleDateFormat, Date, and Calendar, don’t. Avoid these legacy date-time classes. Hey were designed by people who did not understand date-time handling. They were supplanted years ago by the modern java.time classes defined in JSR 310. Sun, Oracle, and the JCP community all gave up on those classes. I suggest you do the same.
In your code:
long ts = Clock.systemUTC().millis();
Instant instant = Instant.ofEpochMilli(ts);
That is the same as doing this:
Instant.now().truncatedTo( ChronoUnit.MILLISECONDS )
In your code:
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, ZoneOffset.UTC);
(A) When working with mere offsets rather than time zones, use OffsetDateTime class. The ZonedDateTime class is for working with time zones.
(B) A briefer way to adjust from Instant to a zoned moment was shown above:
myInstant.atZone( z )
The answer was only setting the timezone to UTC -
DateTimeFormatterBuilder dateTimeFormatterBuilder = new DateTimeFormatterBuilder().append(DateTimeFormatter.ofPattern("uuuu-MM-dd")).appendLiteral(" ")
.append(DateTimeFormatter.ofPattern("HH:mm:ss")).parseLenient();
long ts = Clock.systemUTC().millis();
System.out.println(ts);
Instant instant = Instant.ofEpochMilli(ts);
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, ZoneOffset.UTC);
String str = zonedDateTime.format(dateTimeFormatterBuilder.toFormatter());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
*******
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
*******
long timestamp = simpleDateFormat.parse(str).getTime();
System.out.println(timestamp);
} catch (ParseException e) {
e.printStackTrace();
}
The dateTimeFomatter builder uses format without milliseconds and without timezone.
That's why the str value contain no information about them.
Then simpleDateFormat.parse(str) uses timezone of JVM which is UTC+02:00 in this case.
Trace what is going on:
Instant instant = Instant.now();
// => 2021-12-09 15:58:22.798 +00:00
String str = zonedDateTime.format(dateTimeFormatterBuilder.toFormatter());
// => "2021-12-09 15:58:22"
simpleDateFormat.parse(str);
// => 2021-12-09 15:58:22.000 +02:00
You just need to fix the pattern (add millis .SSS and timezone XXX parts) to make the results consistent as expected:
DateTimeFormatter.ofPattern("HH:mm:ss.SSSXXX")
// and something similar for SimpleDateFormat if needed
Parsing Instant from a custom formatted string.
This example shows how to parse Instant from serialized time assuming that there is a fixed timezone for all cases.
var serializedDateTime = "2020-01-01 10:20:30";
var zoneId = ZoneOffset.UTC; // may be any other zone
var format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
var instant = LocalDateTime
.parse(serializedDateTime, format)
// LocalDateTime is unzoned, just representation of (date + time) numbers in a single object
.atZone(zoneId)
// apply a zone to get ZonedDateTime (point in space-time on Earth)
.toInstant();
// convert to Instant (the same point adjusted to UTC+00:00)
Let me guess, your timezone is UTC+2?
simpleDateFormat.parse(str) assume that your date in current system timezone, but it is in UTC.
How do I get the current date and time in Java?
I am looking for something that is equivalent to DateTime.Now from C#.
Just construct a new Date object without any arguments; this will assign the current date and time to the new object.
import java.util.Date;
Date d = new Date();
In the words of the Javadocs for the zero-argument constructor:
Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.
Make sure you're using java.util.Date and not java.sql.Date -- the latter doesn't have a zero-arg constructor, and has somewhat different semantics that are the topic of an entirely different conversation. :)
The Java Date and Calendar classes are considered by many to be poorly designed. You should take a look at Joda Time, a library commonly used in lieu of Java's built-in date libraries.
The equivalent of DateTime.Now in Joda Time is:
DateTime dt = new DateTime();
Update
As noted in the comments, the latest versions of Joda Time have a DateTime.now() method, so:
DateTime dt = DateTime.now();
tl;dr
Instant.now()
java.time
The java.util.Date class has been outmoded by the new java.time package (Tutorial) in Java 8 and later. The old java.util.Date/.Calendar classes are notoriously troublesome, confusing, and flawed. Avoid them.
ZonedDateTime
Get the current moment in java.time.
ZonedDateTime now = ZonedDateTime.now();
A ZonedDateTime encapsulates:
Date.
Time-of-day, with a fraction of a second to nanosecond resolution.
Time zone.
If no time zone is specified, your JVM’s current default time zone is assigned silently. Better to specify your desired/expected time zone than rely implicitly on default.
ZoneId z = ZoneId.of( "Pacific/Auckland" );
ZonedDateTime zdt = ZonedDateTime.now( z );
UTC
Generally better to get in the habit of doing your back-end work (business logic, database, storage, data exchange) all in UTC time zone. The code above relies implicitly on the JVM’s current default time zone.
The Instant class represents a moment in the timeline in UTC with a resolution of nanoseconds.
Instant instant = Instant.now();
The Instant class is a basic building-block class in java.time and may be used often in your code.
When you need more flexibility in formatting, transform into an OffsetDateTime. Specify a ZoneOffset object. For UTC use the handy constant for UTC.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );
Time Zone
You easily adjust to another time zone for presentation to the user. Use a proper time zone name, never the 3-4 letter codes such as EST or IST.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime nowMontreal = instant.atZone( z );
Generate a String representation of that date-time value, localized.
String output = DateTimeFormatter
.ofLocalizedDate( FormatStyle.FULL )
.withLocale( Locale.CANADA_FRENCH )
.format ( nowMontreal );
Instant
Or, to stay in UTC, use Instant. An Instant object represents a moment on the timeline, to nanosecond resolution, always in UTC. This provides the building block for a zoned date-time, along with a time zone assignment. You can think of it conceptually this way:
ZonedDateTime = Instant + ZoneId
You can extract an Instant from a ZonedDateTime.
Instant instantNow = zdt.toInstant();
You can start with an Instant. No need to specify a time zone here, as Instant is always in UTC.
Instant now = Instant.now();
I prefer using the Calendar object.
Calendar now = GregorianCalendar.getInstance()
I find it much easier to work with. You can also get a Date object from the Calendar.
http://java.sun.com/javase/6/docs/api/java/util/GregorianCalendar.html
In Java 8 it's:
ZonedDateTime dateTime = ZonedDateTime.now();
import java.util.Date;
Date now = new Date();
Note that the Date object is mutable and if you want to do anything sophisticated, use jodatime.
java.lang.System.currentTimeMillis(); will return the datetime since the epoch
import org.joda.time.DateTime;
DateTime now = DateTime.now();
If you create a new Date object, by default it will be set to the current time:
import java.util.Date;
Date now = new Date();
Java has always got inadequate support for the date and time use cases. For example, the existing classes (such as java.util.Date and SimpleDateFormatter) aren’t thread-safe which can lead to concurrency issues. Also there are certain flaws in API. For example, years in java.util.Date start at 1900, months start at 1, and days start at 0—not very intuitive. These issues led to popularity of third-party date and time libraries, such as Joda-Time. To address a new date and time API is designed for Java SE 8.
LocalDateTime timePoint = LocalDateTime.now();
System.out.println(timePoint);
As per doc:
The method now() returns the current date-time using the system
clock and default time-zone, not null. It obtains the current
date-time from the system clock in the default time-zone. This will
query the system clock in the default time-zone to obtain the current
date-time. Using this method will prevent the ability to use an
alternate clock for testing because the clock is hard-coded.
what is the best way to set a XMLGregorianCalendar value from a Calendar date?
posting.setXMLGregorianCalendar(message.getCreateDate());
here my class:
Message.java
private Calendar createDate;
public Calendar getCreateDate() {
return createDate;
}
You can try out this:
Calendar createDate = Calendar.getInstance();
Date cDate = createDate.getTime();
GregorianCalendar c = new GregorianCalendar();
c.setTime(cDate);
XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
tl;dr
DatatypeFactory.newInstance().newXMLGregorianCalendar(
GregorianCalendar.from(
ZonedDateTime.now(
ZoneId.of( "Pacific/Auckland" )
)
)
)
A moment requires a time zone
The XMLGregorianCalendar, GregorianCalendar, and Calendar classes all represent a moment, that is, a date, a time-of-day, and an assigned time zone. Stay aware of the issue of time zone. If you fail to address zone explicitly, the JVM’s current default time zone will be assigned implicitly.
Specify a proper time zone name in the format of Continent/Region, such as America/Edmonton, Africa/Tunis, or Europe/Moscow. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
java.time
These …Calendar classes are also terrible. Sun, Oracle, and the JCP community gave up on them years ago with the adoption of JSR 310… and so should you. Use only the java.time classes for your business logic.
ZoneId z = ZoneId.of( "Africa/Casablanca" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ; // Capture the current moment as seen through the wall-clock time used by the people of a particular region (a time zone).
Convert
If interacting with old code not yet updated to java.time, convert between legacy classes and modern classes. Look to new methods added to the old classes.
A ZonedDateTime object can be converted to a GregorianCalendar object (a subclass of Calendar) by calling GregorianCalendar.from( ZonedDateTime ).
GregorianCalendar gregCal = GregorianCalendar.from( zdt ) ;
A GregorianCalendar can be converted to a XMLGregorianCalendar, but we have to go to one extra step. The XMLGregorianCalendar class itself lacks a converter method from GregorianCalendar. A helper class can get the job done, DatatypeFactory, as shown in this Answer by Stephen Colebourne, “JodaStephen”, the inventor of java.time.
XMLGregorianCalendar xmlGregCal = DatatypeFactory.newInstance().newXMLGregorianCalendar( gregCal );
Not that I recommend it, but you can combine this into a one-liner as seen in the tl;dr section up top.
I have several time zone strings in UTC format, such as "UTC+08:00", "UTC-05:00", the question is how can i convert these utc format strings to the java.util.TimeZone in Java?
I have tried to convert by ZoneId as follows, but it did not work:
ZoneId zoneId = ZoneId.of("UTC+08:00");
TimeZone timeZone = TimeZone.getTimeZone(zoneId);
I know TimeZone timeZone = TimeZone.getTimeZone("Asia/Shanghai"); would work, but I do not know the mapping between "UTC+08:00" and "Asia/Shanghai"
tl;dr
Do not use TimeZone class (now legacy).
Use ZoneOffset and ZoneId instead.
Example:
ZoneOffset.of( "+08:00" )
Use java.time.ZoneId, not TimeZone
The troublesome old date-time classes bundled with the earliest versions of Java are now legacy, supplanted by the java.time classes. Among these old legacy classes is TimeZone, now supplanted by ZoneId and ZoneOffset.
An offset-from-UTC is a number of hours and minutes adjustment ahead of, or behind, UTC. This is represented by the ZoneOffset class.
A time zone is a collection of offsets, the history of changes in the offset used by a particular region in determining their wall-clock time. This is represented by the ZoneId class.
Using a time zone is always preferable to an offset as a zone has the offset plus so much more information. But your examples are only mere offsets. So use the ZoneOffset to parse the strings after deleting the characters UTC.
String input = "UTC+08:00".replace( "UTC" , "" ) ;
ZoneOffset offset = ZoneOffset.of( input ) ;
Do not guess the time zone
You cannot assume that a particular offset implies a particular time zone. Many zones may have used a particular offset in the past, present, or future. So you should not guess the zone.
Take, for example, the offset of +08:00. That offset is currently used by several different time zones including Asia/Shangai, Asia/Macao, and Australia/Perth.
If you are certain a particular zone was intended for a date-time value, apply it to get a ZonedDateTime. But do not guess.
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.
Instant instant = Instant.now() ;
ZoneId z = ZoneId.of( "Asia/Shanghai" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
If you do not know for certain the intended time zone and have only an offset, use the offset to get an OffsetDateTime.
Instant instant = Instant.now() ;
ZoneOffset offset = ZoneOffset.of( "+08:00" ) ;
OffsetDateTime odt = instant.atOffset( offset ) ;
Convert
Best to avoid the old legacy class TimeZone. But if you must use that class to work with old code not yet updated for the java.time classes, you can convert to/from a ZoneId. Use the new conversion methods added to the old classes.
TimeZone myLegacyTimeZone = TimeZone.getTimeZone( myModernZoneId );
…and…
ZoneId z = myLegacyTimeZone.toZoneId() ;
Note that ZoneOffset is a subclass of ZoneId. Normally, we ignore that inheritance relationship. If you have only a mere offset such as +08:00, use ZoneOffset. If you have a full time zone such as Asia/Shanghai, use ZoneId. One exception to this rule is for this conversion to/from TimeZone where only the superclass ZoneId is recognized.
If you strip the UTC, you can parse it as a ZoneOffset, which extends ZoneId
ZoneId zoneId = ZoneOffset.of("+08:00")
Since you can use the modern classes in the java.time package, I recommend you stick with them and avoid the outdated classes like TimeZone, SimpleDateFormat and Date. I am mostly repeating what #Basil Bourque already said in his answer, but also wanted to demonstrate how nicely his suggestion fits into your context:
DateTimeFormatter format = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm");
ZonedDateTime dateTime = LocalDateTime.parse(dateTimeString, format).atZone(zoneId);
Instant i = dateTime.toInstant();
System.out.println(dateTime + " -> " + i);
I have also demonstrated that you may convert the ZonedDateTime to an Instant in case you need that. The snippet prints
2017-05-05T05:05+08:00[UTC+08:00] -> 2017-05-04T21:05:00Z
If you are sure your date-time string and your zone string belong together, there is no need to go through String.replace() for removing UTC from the beginning of the zone string.
I am parsing the string independently of the time zone and then combining it with the zone offset information afterward. I think it’s more natural than having to know the zone for parsing.
In case you need an oldfashioned Date, for example for a call to some legacy code, that’s easy enough:
Date d = Date.from(i);
The old classes are troublesome
Even though I know the old classes have a tendency to show unwanted behaviour without telling you that anyting is wrong, I was still negatively surprised to learn that the code in your question didn’t work. It gives a time zone of GMT! It’s documented that this is a possibility, though, in the documentation of TimeZone.getTimeZone(ZoneId):
Returns:
the specified TimeZone, or the GMT zone if the given ID cannot be understood.
One may stil wonder how a simple time zone like UTC+08:00 can be “not understood”.
How do I get the current date and time in Java?
I am looking for something that is equivalent to DateTime.Now from C#.
Just construct a new Date object without any arguments; this will assign the current date and time to the new object.
import java.util.Date;
Date d = new Date();
In the words of the Javadocs for the zero-argument constructor:
Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.
Make sure you're using java.util.Date and not java.sql.Date -- the latter doesn't have a zero-arg constructor, and has somewhat different semantics that are the topic of an entirely different conversation. :)
The Java Date and Calendar classes are considered by many to be poorly designed. You should take a look at Joda Time, a library commonly used in lieu of Java's built-in date libraries.
The equivalent of DateTime.Now in Joda Time is:
DateTime dt = new DateTime();
Update
As noted in the comments, the latest versions of Joda Time have a DateTime.now() method, so:
DateTime dt = DateTime.now();
tl;dr
Instant.now()
java.time
The java.util.Date class has been outmoded by the new java.time package (Tutorial) in Java 8 and later. The old java.util.Date/.Calendar classes are notoriously troublesome, confusing, and flawed. Avoid them.
ZonedDateTime
Get the current moment in java.time.
ZonedDateTime now = ZonedDateTime.now();
A ZonedDateTime encapsulates:
Date.
Time-of-day, with a fraction of a second to nanosecond resolution.
Time zone.
If no time zone is specified, your JVM’s current default time zone is assigned silently. Better to specify your desired/expected time zone than rely implicitly on default.
ZoneId z = ZoneId.of( "Pacific/Auckland" );
ZonedDateTime zdt = ZonedDateTime.now( z );
UTC
Generally better to get in the habit of doing your back-end work (business logic, database, storage, data exchange) all in UTC time zone. The code above relies implicitly on the JVM’s current default time zone.
The Instant class represents a moment in the timeline in UTC with a resolution of nanoseconds.
Instant instant = Instant.now();
The Instant class is a basic building-block class in java.time and may be used often in your code.
When you need more flexibility in formatting, transform into an OffsetDateTime. Specify a ZoneOffset object. For UTC use the handy constant for UTC.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );
Time Zone
You easily adjust to another time zone for presentation to the user. Use a proper time zone name, never the 3-4 letter codes such as EST or IST.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime nowMontreal = instant.atZone( z );
Generate a String representation of that date-time value, localized.
String output = DateTimeFormatter
.ofLocalizedDate( FormatStyle.FULL )
.withLocale( Locale.CANADA_FRENCH )
.format ( nowMontreal );
Instant
Or, to stay in UTC, use Instant. An Instant object represents a moment on the timeline, to nanosecond resolution, always in UTC. This provides the building block for a zoned date-time, along with a time zone assignment. You can think of it conceptually this way:
ZonedDateTime = Instant + ZoneId
You can extract an Instant from a ZonedDateTime.
Instant instantNow = zdt.toInstant();
You can start with an Instant. No need to specify a time zone here, as Instant is always in UTC.
Instant now = Instant.now();
I prefer using the Calendar object.
Calendar now = GregorianCalendar.getInstance()
I find it much easier to work with. You can also get a Date object from the Calendar.
http://java.sun.com/javase/6/docs/api/java/util/GregorianCalendar.html
In Java 8 it's:
ZonedDateTime dateTime = ZonedDateTime.now();
import java.util.Date;
Date now = new Date();
Note that the Date object is mutable and if you want to do anything sophisticated, use jodatime.
java.lang.System.currentTimeMillis(); will return the datetime since the epoch
import org.joda.time.DateTime;
DateTime now = DateTime.now();
If you create a new Date object, by default it will be set to the current time:
import java.util.Date;
Date now = new Date();
Java has always got inadequate support for the date and time use cases. For example, the existing classes (such as java.util.Date and SimpleDateFormatter) aren’t thread-safe which can lead to concurrency issues. Also there are certain flaws in API. For example, years in java.util.Date start at 1900, months start at 1, and days start at 0—not very intuitive. These issues led to popularity of third-party date and time libraries, such as Joda-Time. To address a new date and time API is designed for Java SE 8.
LocalDateTime timePoint = LocalDateTime.now();
System.out.println(timePoint);
As per doc:
The method now() returns the current date-time using the system
clock and default time-zone, not null. It obtains the current
date-time from the system clock in the default time-zone. This will
query the system clock in the default time-zone to obtain the current
date-time. Using this method will prevent the ability to use an
alternate clock for testing because the clock is hard-coded.