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.
Related
I am using ZonedDateTime to convert GMT timestamp to America/Phoenix timestamp,
Here is my implementation
public static ZonedDateTime convertGMTTimestampToLocalTime(Timestamp gmtTime, String timeZone) throws Exception
{
ZonedDateTime atZone =Instant
.ofEpochMilli( // Parse a count of milliseconds since 1970-01-01T00:00Z.
gmtTime.getTime()
) // Returns a `Instant` object.
.atZone(
ZoneId.of( timeZone )
); // Returns a `ZonedDateTime` object.
return atZone;
}
This gives proper result when I test in local but when I test it remotely (server with docker container) it gives wrong result.
If I do a transaction at 6-Jan-2021 8:00PM (America/Phoenix) it should give 6-Jan-2021 instead it display 7-Jan-2021. My server is in MST
What am I missing, isn't the server supposed to print the date according to the specified time zone. Any help would be appreciated. Thanks.
Avoid legacy date-time classes
Never use the terrible legacy classes Timestamp, Date, Calendar, etc. These were years ago supplanted by the modern java.time classes defined in JSR 310.
Use java.time
If handed an object of that class, immediately convert to Instant. The Instant class represents a moment as seen in in UTC, with an offset of zero hours-minutes-seconds.
Instant instant = myTimestamp.toInstant() ;
Adjust to your desired time zone.
ZoneId z = ZoneId.of( "America/Phoenix" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Extract the date portion.
LocalDate ld = zdt.toLocalDate() ;
Generate text representing the value of that LocalDate object.
String iso8601 = ld.toString() ;
Or automatically localize.
Locale locale = Locale.US ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT ).
String localized = ld.format( f ) ;
You said:
My server is in MST
First, servers should generally be kept to a default time zone of UTC, that is no zone, just an offset of zero hours-minutes-seconds.
Secondly, as a Java programmer, write your code without depending on the default time zone. Specify explicitly the desired time zone by passing the otherwise optional time zone argument to the various date-time methods.
Thirdly, MST is not a real time zone.
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.
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.
sample:
Long timeStamp = 1466058808;
Time time = new Time(timeStamp );
DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
System.out.println(format.format(time));
print is: 2016-05-31 08:19:07
How can I get expected results is : 2016-05-31 00:00:00
Thanks!
And finally get the time stamp of 2016-05-31 00:00:00 This is what i want
So anyone know how to make it?
Simple, use:
DateFormat format = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
Or if you want a long (and have java 8):
LocalDateTime.ofEpochSecond(1466058808, 0, ZoneOffset.UTC).toLocalDate().atStartOfDay().toEpochSecond(ZoneOffset.UTC)
java.time
The Answer by krzyk is close but ignores the crucial issue of time zone. Let's try that again using the java.time framework built into Java 8 and later. Much of java.time functionality is back-ported to Java 6 & 7 (ThreeTen-Backport) and further adapted to Android (ThreeTenABP).
Count of seconds from epoch
You do not say so in the Question, but we assume the Long of 1466058808 is a number of whole seconds from the epoch of first moment of 1970 in UTC.
Instant
First we convert that to an Instant, a moment on the timeline in UTC.
Instant instant = Instant.ofEpochSecond( 1466058808L );
Time Zone
Determining a date, and the start of the day, depends on a time zone. For any given moment, the date can vary around the world by time zone. A few moments after midnight in Paris is still “yesterday” in Montréal.
ZonedDateTime
You can make wide use of Instant in your code. Generally best practice is to perform business logic, data storage, logging, and so on in UTC. Apply a time zone only where required such as display to a user. Apply a ZoneId to get a ZonedDateTime.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
Using LocalDate for start-of-day
To get the start of the day we need to go through the LocalDate class. Note that we should always pass the optional time zone argument. If omitted, the JVM’s current default time zone is implicitly applied. That default can change at any time, even during runtime, as any code in any app of the JVM can make a call to TimeZone.setDefault. Better to be specific.
LocalDate localDate = zdt.toLocalDate();
ZonedDateTime startOfDay = localDate.atStartOfDay( zoneId );
Note that you should not assume the day starts at 00:00:00.0. Daylight Saving Time (DST) may mean the day starts at a different wall-clock time.
One-liner
I do not recommend doing so, but you can combine all this into a single line.
ZonedDateTime startOfDay = ZonedDateTime.ofInstant( Instant.ofEpochSecond( 1466058808L ) , ZoneId.of( "America/Montreal" ) ).toLocalDate().atStartOfDay( ZoneId.of( "America/Montreal" ) );
use a Calendar, so you can extract date properties:
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(millis);
//getting the desired properties
cal.get(Calendar.YEAR);
cal.get(Calendar.MONTH);
cal.get(Calendar.DAY_OF_MONTH);
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.