I am trying to change the date format from a JSON response, but I keep getting java.text.ParseException.
This is the date from the server 2015-02-03T08:37:38.000Z and I want it to show as 2015/02/03 That's yyyy-MM-dd. And I did this.
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
String dateResp = transactionItem.get(position).getDate();
try {
Date date = df1.parse(dateResp);
transDate.setText(dateFormatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
But the exception keeps showing.
You must escape the Z:
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
Try to use this for formatting purpose instead of your provided formatting string. It should work nicely :)
tl;dr
Instant.parse( "2015-02-03T08:37:38.000Z" )
.atZone( ZoneId.of( "America/Montreal" ) )
.toLocalDate()
.toString() // 2015-02-03
Using java.time
The modern way to handle date-time work is with the java.time classes.
Your input string format happens to comply with the ISO 8601 standard. The java.time classes use ISO 8601 formats by default when parsing/generating strings that represent date-time values. So no need to specify a formatting pattern at all.
Parse that string as an 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.parse( "2015-02-03T08:37:38.000Z" ) ;
To extract a date, you must specify a time zone. For any given moment the date varies around the globe by zone. For example, a moment after midnight in Paris France is a new day while still “yesterday” in Montréal Canada.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
You want only the date portion without the time of day. So extract a LocalDate. While a LocalDate lacks any concept of offset-from-UTC or time zone, the toLocalDate method respects the ZonedDateTime object’s time zone in determining the date.
LocalDate ld = zdt.toLocalDate();
You seem to want standard ISO 8601 format, YYYY-MM-DD. Simply call toString without need to specify a formatting pattern.
String output = ld.toString();
2015-02-03
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 and 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 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.
Related
I want to convert string date to Cassandra time stamp format
Example date
String inputDate="20170525"
You need to convert your string to Date.
Java Date type maps cassandra timestamp type
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
Date date = dateFormat.parse("20170525");
Now you have the date you can insert or query with it in prepared statement
Note : You don't have any timezone. So default timezone will be used. If you want to specify the timezone use dateFormat.setTimeZone(TimeZone zone) method
First, parse that input string as a LocalDate.
LocalDate ld = LocalDate.parse( "20170525" , DateTimeFormatter.BASIC_ISO_DATE ) ;
For a date-only value without time-of-day, you should be using type Date in Cassandra according to this documentation.
You can exchange data as strings using standard ISO 8601 format. The java.time classes use the standard formats by default. So no need to specify a formatting pattern.
String output = ld.toString() ;
2017-05-25
If you really want to store in the timestamp, you must specify a time-of-day. Perhaps you want the first moment of the day. Determining that specific moment on the timeline that requires a time zone. Do not assume the first moment occurs at 00:00:00. Anomalies such as Daylight Saving Time mean the time may be another value such as 01:00:00.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ld.atStartOfDay( z ) ;
zdt.toString(): 2017-05-25T00:00:00-04:00[America/Montreal]
Cassandra stores the Timestamp field only as UTC. So we need to adjust the ZonedDateTime from our desired time zone to UTC. The easiest way to do that is extract a Instant. The Instant class is always in UTC by definition.
Instant instant = zdt.toInstant() ;
Generate a string in standard ISO 8601 format for Cassandra. Notice how the hour jumps from zero to four. Our time zone America/Montreal is four hours behind UTC on that date. So getting to UTC means adding four hours, 0 + 4 = 4.
String output = instant.toString() ;
2017-05-25T04:00:00Z
Going the other way when your retrieve this value.
Instant instant = Instant.parse( "2017-05-25T04:00:00Z" ) ;
ZonedDateTime zdt = instant.atZone( z );
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.
I am getting time in string like this "2011-02-27T10:03:33.099-06:00" which is of xml dateTime type. I also have timezone of TimeZone type. How should I convert the dateTime to GregorianCalendar java type in that timezone.
Java has built in code to parse xml datetimes: use DatatypeConverter.parseDateTime(). that will return a Calendar in the parsed TimeZone. you can then set the Calendar TimeZone to your desired target TimeZone for whatever you need to do next.
sdf = new java.text.SimpleDateFormat ("yyyy-MM-dd'T'HH:mm:ss.S");
parses everything, except the trailing TZ.
sdf.parse (sd);
res168: java.util.Date = Sun Feb 27 10:03:33 CET 2011
From the api docs, I would expect
sdf = new java.text.SimpleDateFormat ("yyyy-MM-dd'T'HH:mm:ss.SSSz");
to be used to read the -06:00 in the end. But I see, that there is either an offset in the form 0700 expected, or with a prefix of GMT for example "GMT-04:00". So you have to insert that GMT-thingy yourself:
sdf.parse (sd.replaceAll ("(......)$", "GMT$1"))
SDF.parse (str) returns a Date, which has to be converted into a GC:
GregorianCalendar calendar = new GregorianCalendar ();
calendar.setTime (date);
tl;dr
OffsetDateTime.parse( "2011-02-27T10:03:33.099-06:00" )
java.time
The modern approach uses the java.time classes that supplanted the troublesome old legacy date-time classes. Specifically, GregorianCalendar was replaced by ZonedDateTime for a time zone, and OffsetDateTime for a mere offset-from-UTC.
ISO 8601
Your input string happens to comply with the ISO 8601 standard format.
The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.
OffsetDateTime
Your input string contains an offset-from-UTC, but not a time zone. So parse as an OffsetDateTime.
OffsetDateTime odt = OffsetDateTime.parse( "2011-02-27T10:03:33.099-06:00" ) ;
ZonedDateTime
If you know for certain the intended time zone, apply a ZoneId to produce a ZonedDateTime.
A time zone is always preferable to a mere offset. A zone is a history of past, present, and future changes to the offset used by the people of a particular region.
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( "Pacific/Galapagos" ) ;
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;
Converting legacy ↔ modern
If you must have a GregorianCalendar object to inter-operate with old code not yet updated to java.time, you can convert. Look to new methods added to the old classes.
GregorianCalendar myGregCal = GregorianCalendar.from( zdt ) ;
And going the other direction…
ZonedDateTime zdt = myGregCal.toZonedDateTime() ;
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.
Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.
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 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.
I am trying to read the system date in CST time zone using Java. I tried the below code but whenever I use formatter.parse() it is returning time in EST time zone.
private Date getTodayInCST() {
Calendar currentdate = Calendar.getInstance();
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
TimeZone obj = TimeZone.getTimeZone("CST");
formatter.setTimeZone(obj);
String today = formatter.format(currentdate.getTime());
try {
return formatter.parse(today);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
tl;dr
ZonedDateTime.now(
ZoneId.of( "America/Chicago" )
)
Details
I am trying to read the system date in CST time zone
By “CST”, do you mean Central Standard Time in North America, or China Standard Time?
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 as seen above with CST.
ZoneId z = ZoneId.of( "America/Chicago" ) ;
java.time
You are using troublesome old date-time classes that are now legacy. Supplanted by the java.time classes.
Get the current moment in UTC. 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() ;
2018-02-26T05:45:24.213610Z
Adjust into another time zone. Same moment, same point on the timeline, different wall-clock time.
ZonedDateTime zdt = instant.atZone( z ) ;
zdt.toString(): 2018-02-25T23:45:24.213610-06:00[America/Chicago]
The above strings are in standard ISO 8601 format. The ZonedDateTime class extends that standard wisely to append the name of the zone in square brackets.
If you want to generate String objects in other formats, use DateTimeFormatter.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu HH:mm:ss" ) ;
String output = zdt.format( f ) ;
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.
Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.
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 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.
java.util.Date objects do not contain any timezone information by themselves - you cannot set the timezone on a Date object. The only thing that a Date object contains is a number of milliseconds since the "epoch" - 1 January 1970, 00:00:00 UTC.
If you want to set timezone try it this way
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
format.setTimeZone(TimeZone.getTimeZone("CST"));
System.out.println(format.format(new Date()));
If want to the code to provide the current time considering the daylight saving adjustment from CST to CDT or vice versa ,you can use the
"CST6CDT" timezone. in place of "CST" in SimpleDateFormat.
SimpleDateFormat cstCdtFormat=new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
cstCdtFormat.setTimeZone(TimeZone.getTimeZone("CST6CDT"));
System.out.println(cstCdtFormat.format(new Date()));
I am using java.text.DateFormat in order to display the date and time for a user of my application. Below is my code to test the output.
The issue is that the date is being displayed as 1970 (see output below). How can I update this to the current date and time.
Current Output:
1 Jan 1970 01:00:00
Current code:
DateFormat[] formats = new DateFormat[] {
DateFormat.getDateTimeInstance(),
};
for (DateFormat df : formats) {
Log.d("Dateformat", "Date format: " + (df.format(new Date(0))));
}
Alternatively if the above is not possible, I am able to get the current time and date using the following method:
Time now = new Time();
now.setToNow();
String date= now.toString();
Output:
20140722T133458Europe/London(2,202,3600,1,1406032498)
How can I adjust this in order to make it readable for a user?
Just write new Date() instead of new Date(0) in your first snippet. When you write new Date(some number) it makes a date which is that many milliseconds after 1/1/1970 00:00:00Z
Use this -
String S = new SimpleDateFormat("MM/dd/yyyy").format(System.currentTimeMillis());
tl;dr
Instant.now()
.atZone( ZoneId.of( "America/Montreal" ) )
.format( DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL )
.withLocale( Locale.CANADA_FRENCH )
)
Instant
The accepted Answer by Wallace is correct.
But know that you are using troublesome old date-time classes now supplanted by the java.time classes.
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(); // Current moment in UTC.
To generate a String representing that moment formatting according to the ISO 8601 standard, simply call toString.
ZonedDateTime
To view the same moment through the lens of some region’s wall-clock time, apply a ZoneId to get a ZonedDateTime.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z ); // Adjust from UTC to a specific time zone. Same moment, different wall-clock time.
DateTimeFormatter
For presentation to the user, let java.time automatically localize using the DateTimeFormatter class.
To localize, specify:
FormatStyle to determine how long or abbreviated should the string be.
Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, and such.
Example:
Locale l = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( l );
String output = zdt.format( f );
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, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
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 and 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 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….
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.
My class has 2 properties that make up its date:
java.util.Date date;
String timeZone;
How can I see if this date is before the current time on the server?
Basically I want to write something like this, but take timeZone into account:
return date.before(new Date());
Date stores internally as UTC, so your timeZone variable is not necessary. You can simply use Date.before(Date).
Calendar startCalendar = Calendar.getInstance();
int startTimeZoneOffset = TimeZone.getTimeZone(timeZone).getOffset(startDate.getTime()) / 1000 / 60;
startCalendar.setTime(startDate);
startCalendar.add(Calendar.MINUTE, startTimeZoneOffset);
Calendar nowCalendar = Calendar.getInstance();
int nowTimeZoneOffset = nowCalendar.getTimeZone().getOffset(new Date().getTime()) / 1000 / 60;
nowCalendar.setTime(new Date());
nowCalendar.add(Calendar.MINUTE, nowTimeZoneOffset);
return startCalendar.before(nowCalendar);
tl;dr
Use Instant class, which is always in UTC. So time zone becomes a non-issue.
someInstant.isBefore( Instant.now() )
java.time
The modern approach uses the java.time classes that supplanted the terrible Date & Calendar classes.
As the correct Answer by Kuo stated, your java.util.Date is recording a moment in UTC. So no need for a time zone.
Likewise, its replacement, the java.time.Instant class, also records a moment in UTC. So no time zone needed.
Instant instant = Instant.now() ; // Capture current in UTC.
So all you need as member variables on your class is Instant.
public class Event {
Instant when ;
…
}
To compare Instant objects, use the isAfter, isBefore, and equals methods.
someInstant.isBefore( Instant.now() )
For presentation in a time zone expected by the user, assign a ZoneId to get a ZonedDateTime object. The Instant and the ZonedDateTime both represent the same moment, the same point on the timeline, but viewed through different wall-clock time.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ; // Same moment, different wall-clock time.
String output = zdt.toString() ; // Generate text in standard ISO 8601 format, wisely extended to append the name of the zone in square brackets.
Or let java.time automatically localize output. To localize, specify:
FormatStyle to determine how long or abbreviated should the string be.
Locale to determine:
The human language for translation of name of day, name of month, and such.
The cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
Example:
Locale l = Locale.CANADA_FRENCH ; // Or Locale.US, Locale.JAPAN, etc.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL )
.withLocale( l );
String output = zdt.format( f );
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.
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.