I am trying to send a date via JSON using a format like "date":"2018-01-03" but in my Java code I get 2018-01-03 02:00:00 and not 2018-01-03 00:00:00 as I would expect. Seems like it is adding some timezone to my date. Is this alright or am I missing something?
To represent a date-only value, use a date-only type rather than a date+time-of-day type.
LocalDate
LocalDate represents a date without a time-of-day and without a time zone.
LocalDate ld = LocalDate.of( "2018-01-03" ) ;
ZonedDateTime
To get the first moment of the day, specify a time zone.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = ld.atStartOfDay( z ) ;
Instant
To view that same moment in UTC, extract an Instant object from the ZonedDateTime.
Instant instant = zdt.toInstant() ;
These topics have been discussed many many times already. Search Stack Overflow for more info.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
From the Java API "The class Date represents a specific instant in time, with millisecond precision." When you create a Date you automatically get a date with a time. If you want to send just the date you have some options: 1. Convert the date to a string on the server side using the desired format. 2. On the client side ignore the time. 3. On the server side, zero the time fields, using methods such as setMinutes(0). But please note that these methods are deprecated in favor of Calendar methods, and further the old Date and Calendar classes are replaced by the Java 8 date and time classes.
Related
In my application i want get some data from server and i should cast date and time!
I receive date and time with this format end_date: "2020-04-08 13:11:14" from server.
I want get now date and time from my device and to calculate with above date (end_date), if this time under 24h i should show for example 15 hour later, but if this time more than 24h i should show 2 days later!
But i don't know how can i it?
Can you help me with send code or send to me other tutorials?!
I searched that but I didn't find anything.
java.time
The modern approach uses java.time classes.
Parse the input string as a LocalDateTime.
To parse, replace the SPACE in the middle with a T to comply with ISO 8601 standard.
String input = "2020-04-08 13:11:14".replace( " " , "T" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;
Your input lacks an indicator of any time zone or offset-from-UTC. So we do not know if this was meant to be 1 PM in Tokyo Japan, 1 PM in Toulouse France, or 1 PM in Toledo Ohio US. So you cannot reliably compare this to the current date and time.
If you want to presume this string was meant to tell time in your time zone, then assign a time zone to get a ZonedDateTime.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime then = ldt.atZone( z ) ;
Capture the current moment in the same zone.
ZonedDateTime now = ZonedDateTime.now( z ) ;
Calculate 24 hours later.
ZonedDateTime twentyFourHoursFuture = now.plusHours( 24 ) ;
Compare.
boolean within24Hours = then.isBefore( twentyFourHoursFuture ) ;
Determine elapsed time using the Duration class.
Duration duration = Duration.between( then , now ) ;
If you want to trust the JVM’s current default time zone, call ZoneId.systemDefault. Beware that this default can be changed by other Java code during execution of your app.
ZoneId z = ZoneId.systemDefault() ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Try using the datetime library, or you can see this answer.
Also if you can choose, it's a good habit to pass the times in UTC from/to the server, it'll save some localization and timezone troubles.
i have a Date field expiryDate with value Thu Nov 21 00:00:00 IST 2019 But i am trying to get the endDate time to the before to the day by removing a millisecond from the time as Thu Nov 20 23:59:59 IST 2019
do we have any methods to remove a millisecond from the given Date.
java.time
Avoid the terrible date-time classes that are now legacy as of JSR 310. Now supplanted by the modern java.time classes.
You can easily convert back and forth. Call new conversion methods addd to the old classes.
Instant instant = myJavaUtilDate.toInstant() ;
And back again.
java.util.Date myJavaUtilDate = Date.from( instant ) ;
Subtract a millisecond.
Instant oneMilliEarlier = instant.minusMillis( 1 ) ;
Half-Open
But I suggest you not take this approach. Do not track a span of time by its last moment.
Your attempt to track the last moment of the day is problematic. You are losing that last millisecond of time. Doing so leaves a gap until the first moment of the next day. And when switching to a finer time slicing such as microseconds used by some systems such as databases like Postgres, and the nanoseconds used by other software such as the java.time classes, you have a worse problem.
A better approach is the Half-Open approach commonly used in date-time handling. The beginning of a span-of-time is inclusive while the ending is exclusive.
So an entire day starts at the first moment of the day, typically at 00:00:00 (but not always!), and runs up to, but does not include, the first moment of the next day.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
ZonedDateTime start = zdt.toLocalDate().atStartOfDay( z ) ;
ZonedDateTime stop = start.plusDays( 1 ) ;
Tip: For working with such spans of time, add the ThreeTen-Extra library to access the Interval class.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
yes. i just tried with the above mehtod getTime() returns milliseconds to the given date.
and substracting a millisecond is giving me a correct output.
new Date(milliseconds) giving me the Date format.
Thanks #Elliott Frisch
I am trying to get current time in other time zone. I used this code for this:
GregorianCalendar calender = new
GregorianCalendar(TimeZone.getTimeZone("Asia/Bangkok"));
System.out.println(calender.getTime());
But, when I am running this code, this code provides the current time in CET as the time in my local machine is in CET.
I am confused. Then why there is scope to provide a TimeZone in constructor?
Ahh, the joys of the Java Date/Time API ...
What you want (aside from a better API, such as Joda Time) is a DateFormat. It can print dates in a time zone you specify. You don't need Calendar for that.
dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Bangkok"));
dateFormat.format(new Date());
Calendar is for time manipulations and calculations. For example "set the time to 10 AM". Then it needs the timezone.
When you are done with these calculations, then you can get the result by calling calendar.getTime() which returns a Date.
A Date is essentially a universal timestamp (in milliseconds since 1970, with no timezone information attached or relevant). If you call toString on a Date it will just print something in your default timezone. For more control, use DateFormat.
What you are doing right now is:
Getting a calendar in Bangkok time zone
get the Date object for this time( which is in ms since some date January 1, 1970, 00:00:00 GMT)
print out this Date in your timezone (Date.toString())
You should use a Formatter class to get the result you want. e.g. SimpleDateFormat
An alternative solution would be to use a less confusing Date/Time library. e.g. JodaTime or the new java.time package of Java8
tl;dr
ZonedDateTime.now( ZoneId.of( "Asia/Bangkok" ) )
java.time
The legacy date-time classes you are using are simply terrible, flawed in design and in implementation, built by people who did not understand date-time handling. Avoid those classes entirely.
Use only the modern java.time classes defined in JSR 310.
ZoneId z = ZoneId.of( "Asia/Bangkok" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Generate text in standard ISO 8601 format, wisely extended to append the name of the time zone in square brackets.
String output = zdt.toString() ;
For other formats, use DateTimeFormatter as seen on hundreds of other Questions and Answers.
See this code run live at IdeOne.com.
2020-02-15T12:27:31.118127+07:00[Asia/Bangkok]
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
I have a Date object in Java. Sometimes the date's year is set to 17. When I go to output it using a SimpleDateFormat, it gets printed out as 0017. All my years are going to be in the 2000's. Is there a way to check if the year is belowe a certain value and then add 2000 to it if it is? Then once you do that, how do you recreate the Date object to use the new year? Seems like everything in the Date object is deprecated.
I would use a Calendar:
Date myDate = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(myDate);
int year = cal.get(Calendar.YEAR);
if(year < 2000)
cal.add(Calendar.YEAR, 2000); // add two thousand years
If you use Calendar or Joda Time (a better choice) you can get and set the year (or other fields)
Your year shouldn't be 17 in the first place. I would try to correct the problem at source rather than patch it later.
First of all, Date.getYear returns CurrentYear - 1900, not 2000, and it looks like you'll want to do that increment every time.
But since it's deprecated, you shouldn't use it in the first place, if possible. The API recommends you use the calendar class instead: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Calendar.html
java.time
If by Date you mean java.util.Date, that terribly designed class in now obsolete, years ago supplanted by the java.time classes defined in JSR 310.
Convert to its replacement, Instant, using new methods added to the old classes.
Instant instant = myJavaUtilDate.toInstant() ;
Both Instant and java.util.Date represent a moment in UTC. For any given moment, both time-of-day and date vary around the globe by zone. If you want to see the date through the wall-clock time of a particular time zone, apply ZoneId to get a ZonedDateTime.
ZoneID z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDatetTime zdt = instant.atZone( z ) ;
Now interrogate for the year.
int year = zdt.getYear() ;
Adjust. If that date in the different year is not valid (February 29 in non leap year), the ZonedDateTime class adjusts.
if( year < 1000 ) {
zdt = zdt.withYear( year + 2000 ) ; // You might also want to check for negative numbers. I'll omit that from this demo.
}
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
I would like to send a Java Calendar object over a web service (soap). I notice that this kind of object is too complex and there should be a better method to send the same information.
What are the basic attributes that should be sended over the web service, so the client can create a Java Calendar out of this attributes?
I'm guessing: TimeZone, Date, and Time?
Also, how can the client recreate the Calendar based on those attributes?
Thanks!
In fact I would go for Timezone tz (timezone the calendar was expressed in), Locale loc (used for data representation purpose) and long time (UTC time) if you want exactly the same object.
In most uses the time is enough though, the receiver will express it with his own timezone and locale.
I suppose the Calendar instance that you would like to send is of type java.util.GregorianCalendar. In that case, you could just use xsd:dateTime. For SOAP, Java will usually bind that to a javax.xml.datatype.XMLGregorianCalendar instance.
Translating between GregorianCalendarand XMLGregorianCalendar:
GregorianCalendar -> XMLGregorianCalendar: javax.xml.datatype.DatatypeFactory.newXMLGregorianCalendar(GregorianCalendar)
XMLGregorianCalendar -> GregorianCalendar: XMLGregorianCalendar.toGregorianCalendar()
The easiest way is to use a long value.
java.util.Calendar.getInstance().getTimeInMillis()
This returns the long value for the date. That value can be used to construct java.util.Date or a Calendar.
tl;dr
Use plain text, in UTC, in standard ISO 8601 format.
Instant.now().toString()
2018-01-23T01:23:45.123456Z
Instant.parse( "2018-01-23T01:23:45.123456Z" )
ISO 8601
The ISO 8601 standard is a well-designed practical set of textual formats for representing date-time values.
2018-01-14T03:57:05.744850Z
The java.time classes use these standard formats by default when parsing/generating strings. The ZonedDateTime class wisely extends the standard to append the name of a time zone in square brackets.
ZoneId z = ZoneId.of( "America/Los_Angeles" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
String output = zdt.toString() ;
2018-01-13T19:56:26.318984-08:00[America/Los_Angeles]
java.time
The java.util.Calendar class is part of the troublesome old date-time classes bundled with the earliest versions of Java. These legacy classes are an awful mess, and should be avoided.
Now supplanted by the modern industry-leading java.time classes.
UTC
Generally best to communicate a moment using UTC rather than a particular time zone.
The standard format for a UTC moment is YYYY-MM-DDTHH:MM:SS.SSSSSSSSSZ where the T separates the year-month-day from the hour-minute-second. The Z on the end is short for Zulu and means UTC.
Instant
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.now() ;
String output = instant.toString() ;
2018-01-14T03:57:05.744850Z
If a particular time zone is crucial, use a ZonedDateTime as shown above.
Parsing
These strings in standard format can be parsed to instantiate java.time objects.
Instant instant = Instant.parse( "2018-01-14T03:57:05.744850Z" ) ;
ZonedDateTime zdt = ZonedDateTime.parse( "2018-01-13T19:56:26.318984-08:00[America/Los_Angeles]" ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time (JSR 310) classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.