Converting gmt to ist unparseable date exception - java

DateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
DateFormat indianFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
indianFormat .setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
String output = null;
try {
Date timestamp = null;
timestamp = utcFormat.parse(createdAt);
output = indianFormat.format(timestamp);
} catch (ParseException e) {
Log.d("ParseError", String.valueOf(e));
}
I want to convert GMT time of format "2020-03-16T18:50:39.656Z" to IST time of same format as GMT but I am getting unparseable exception

The Z at the end of your createdAt value is an ISO 8601 time zone symbol. To parse it, you need to have X in your date format string, not Z. Change your date format string to "yyyy-MM-dd'T'HH:mm:ss.SSSX" and your program will work.
Alternatively, you could keep Z in the date format string, but give your input as "2020-03-16T18:50:39.656+0000" - that is, use the four digit number to represent the time offset in the input, instead of Z.

tl;dr
Instant
.parse(
"2020-03-16T18:50:39.656Z"
)
.atZone(
ZoneId.of( "Asia/Kolkata" )
)
java.time
You are using terrible date-time classes that were supplanted years ago by the modern java.time classes with the adoption of JSR 310.
ISO 8601
Your input string is in standard ISO 8601 format. The Z on the end means UTC (an offset of zero hours-minutes-seconds), and is pronounced “Zulu”.
The java.time classes use ISO 8601 formats by default. So no need to specify a formatting pattern.
Instant
Parse your input as a Instant, representing a moment as seen in UTC.
String input = "2020-03-16T18:50:39.656Z" ;
Instant instant = Instant.parse( input ) ;
ZonedDateTime
Adjust to India time.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
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.
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….

Related

date is shown as fast milliseconds in java and not in proper format

I have the below declaration in java class
abc.setCreated(abcEntity.getCreatedDate());
and if I go deep inside the call inside abc entity
public Date getCreatedDate() {
return new Date(createdDate.getTime());
}
but the date in the outcome of
abc.setCreated(abcEntity.getCreatedDate());
shown as in request "created": 15704064000 and I want it to be shown as the date in DD-MM-YYYY format please advise how to achieve this
You can use SimpleDateFormat in java to get the date in that format. Instead of the time, pass the Date object like bellow.
ex:-
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
String formattedDate = simpleDateFormat.format(new Date());
System.out.println(formattedDate);
tl;dr
Instant.
.ofEpochSecond(
1_570_406_400L
)
.atOffset(
ZoneOffset.UTC
)
.format(
DateTimeFormatter.ofPattern( "dd-MM-uuuu" )
)
07-10-2019
Avoid legacy classes
You are using terrible date-time classes that were supplanted years ago by the modern java.time classes.
java.time
Parse your count of whole seconds since the epoch reference of first moment of 1970 in UTC as a Instant.
Is your example value correct? Perhaps you meant 1,570,406,400.
long seconds = 1_570_406_400L ;
Instant instant = Instant.ofEpochMilli( seconds ) ;
The Instant represents a moment in UTC. Generate a string representing this value in standard ISO 8601 format.
String output = instant.toString() ;
instant.toString(): 2019-10-07T00:00:00Z
To adjust to another time zone, apply a ZoneId to get a ZonedDateTime.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
zdt.toString(): 2019-10-06T20:00-04:00[America/Montreal]
Notice how the date is the 6th rather than the 7th. While at that moment a new day has begun in UTC, it is still “yesterday” in Canada. For any given moment, the date varies around the globe by time zone.
Generate a string a localized format.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" );
String output = zdt.format( f ) ;
output: 06-10-2019
If you want to report the date as seen in UTC rather than a time zone, use OffsetDateTime class. Specify UTC using the constant ZoneOffset.UTC.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" );
String output = odt.format( f ) ;
outputOdt: 07-10-2019
See all that code run live at IdeOne.com.
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.

problems converting date to long

I am pulling data out of an Excel sheet, to load into Hubspot, using Java.
Here is how the data looks:
this date 2018-12-31 becomes Dec 31, 2017 once it's in side Hubspot.
This is wrong!
Here is my code:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date dt = null;
try {
dt = df.parse(member.getUsageEndDate());
} catch (java.text.ParseException e3) {
//dt = null;
e3.printStackTrace();
}
Long l = dt.getTime();
If I open the data in Notepad, it looks like this: 31-May-2018
How can I get this converted properly?
tl;dr
OffsetDateTime.of(
LocalDate.parse( "2018-12-31" ) ,
LocalTime.MIN ,
ZoneOffset.UTC
)
.toInstant()
.toEpochMilli()
1546214400000
Details
Avoid legacy date-time classes
You are using troublesome old date-time classes long ago made legacy by the arrival of the java.time classes built into Java 8 and later.
ISO 8601
Your input string happens to comply with the ISO 8601 standard formats. These formats are used by default in java.time when parsing/generating strings. So no need to specify a formatting pattern.
LocalDate ld = LocalDate.parse( "2018-12-31" ) ;
First moment of the day
Apparently you need the first moment of the day in UTC for that date. Use OffsetDateTime with constant ZoneOffset.UTC.
OffsetDateTime odt = OffsetDateTime.of( ld , LocalTime.MIN , ZoneOffset.UTC ) ;
Dump to console.
System.out.println( "odt.toString(): " + odt );
See this code run live at IdeOne.com.
odt.toString(): 2018-12-31T00:00Z
Count-from-epoch
You appear to want the count of milliseconds since the epoch reference date of first moment of 1970 in UTC, 1970-01-01T00:00Z. Extract an Instant object, the basic building-block class in java.time, and call its handy Instant::toEpochMilli method.
long millisecondsSinceEpoch = odt.toInstant().toEpochMilli() ;
See this code run live at IdeOne.com.
1546214400000
Going the other direction.
Instant instant = Instant.ofEpochMilli( 1_546_214_400_000L ) ;
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.

How to convert Date object format in another Data object format in Java?(No string)

i know that maybe this is a replicated question, but i want to parse a string to convert it into Date object.I'm able to do this by doing:
SimpleDateFormat parser = new SimpleDateFormat("yyyy-M-d (HH:mm:ss.S)");
Date date = parser.parse(propertiesvalue[i]);
And it returns "date" in this format: Fri Jan 30 13:55:00 CET 2015
But i want to return something like:2015-01-30 (13:55:00.00) Data Object (NOT as String Object). I need it to insert Date in local Google Datastore.
String != datetime
Do not conflate a date-time object with a string that may represent its value.
A date-time object has no format. A date-time format represents a moment. A date-time object can generate a string. A date-time object can be created by parsing a string. But the date-time object and the string are always separate and distinct.
Avoid legacy classes
You are using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
Using java.time
Instant instant = Instant.now(); // Current moment in UTC
ZoneId z = ZoneId.of( "Pacific/Auckland" );
ZonedDateTime zdt = instant.atZone( z ); // Same moment viewed as wall-clock time of particular region.
Generate a string to represent that object’s value in a certain format.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-M-d (HH:mm:ss.S)" , Locale.US );
String output = zdt.format( f );
Dump to console.
System.out.println( "instant.toString(): " + instant ); // Standard ISO 8601 format.
System.out.println( "zdt.toString(): " + zdt ); // Standard ISO 8601 format.
System.out.println( "output: " + output ); // Custom format.
See this code run live at IdeOne.com.
instant.toString(): 2017-04-15T06:00:58.521Z
zdt.toString(): 2017-04-15T18:00:58.521+12:00[Pacific/Auckland]
output: 2017-4-15 (18:00:58.5)
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….

Java getting UTC+2 when it would be UTC+1

Last sunday we change the time (-1h) in middle europe. I was making some tests but something does not let me sleep with the java time parser. This is the code
public static void main(String[] args) {
String dateFormatPattern = "yyyy-MM-dd HH:mm:ss";
String dateUtc = "2016-10-09 12:50:00";
SimpleDateFormat dateFormatUtc = new SimpleDateFormat(dateFormatPattern);
dateFormatUtc.setTimeZone(TimeZone.getTimeZone("UTC"));
SimpleDateFormat dateFormatLisboa = new SimpleDateFormat(dateFormatPattern);
dateFormatLisboa.setTimeZone(TimeZone.getTimeZone("Europe/Lisboa"));
SimpleDateFormat dateFormatMadrid = new SimpleDateFormat(dateFormatPattern);
dateFormatMadrid.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));
SimpleDateFormat dateFormatParis = new SimpleDateFormat(dateFormatPattern);
dateFormatParis.setTimeZone(TimeZone.getTimeZone("Europe/Paris"));
System.out.println("UTC: "+dateUtc);
try {
Date d = dateFormatUtc.parse(dateUtc);
System.out.println("Lisboa: "+dateFormatLisboa.format(d));
System.out.println("Madrid: "+dateFormatMadrid.format(d));
System.out.println("Paris: "+dateFormatParis.format(d));
} catch (ParseException e) {
e.printStackTrace();
}
}
And this is the output
UTC: 2016-10-09 12:50:00
Lisboa: 2016-10-09 12:50:00
Madrid: 2016-10-09 14:50:00
Paris: 2016-10-09 14:50:00
Why the difference between UTC and Madrid time are 2 hours? Now in madrid is UTC+1.
Thanks.
The times are correct as the clocks changed on the 30th October at 2am
if you change you code to this
String dateUtc = "2016-11-09 12:50:00";
You get this output, giving the correct 1 hour difference.
UTC: 2016-11-09 12:50:00
Lisboa: 2016-11-09 12:50:00
Madrid: 2016-11-09 13:50:00
Paris: 2016-11-09 13:50:00
The timezone is due to the when the date object is actually referencing. So it is correct for that time
The accepted Answer by French is correct. The values overlapped the cutover in Daylight Saving Time (DST).
I am just pointing out that your code is using old date-time classes, now legacy, supplanted by the java.time classes.
Parse the input value as a LocalDateTime because it lacks any indicator of time zone or offset-from-UTC.
Replace the SPACE in the middle with a T to comply with ISO 8601 format used by default in the java.time classes for parsing/generating strings.
LocalDateTime ldt = LocalDateTime.parse( "2016-10-09 12:50:00".replace( " " , "T" ) );
We know from the business context that UTC is intended for this input string. So assign an offset of UTC.
OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC );
Adjust into a time zone by applying a ZoneId to get a ZonedDateTime.
ZoneId z = ZoneId.of( "Europe/Lisboa" );
ZonedDateTime zdt = odt.atZoneSameInstant( 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.
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.

Java Date Format Parsing

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.

Categories

Resources