Formatting date with time zone. Wrong format - java

I have tried many different types of solutions using java.text.SimpleDateFormat but couldn't quite get it right.
The input string I receive is Tue Nov 5 00:00:00 UTC+0530 2013.
The format that I want is dd-MMM-yy.
Below is the code that I use:
SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM d HH:mm:ss zZ yyyy", Locale.ENGLISH);
date = formatter.parse(s);
System.out.println(date);
I receive an error: unreported exception ParseException; must be caught or declared to be thrown
date = formatter.parse(s);
I tried a lot of change in my formats but still I receive this error. Can anyone please let me know the exact format of the string that I am passing?

Handle Exceptions
You have not handled exceptions in your code. That is why the compiler gives errors. You need to handle the ParseException that may be thrown during parsing.
SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM d HH:mm:ss zZ yyyy", Locale.ENGLISH);
try{
date = formatter.parse(s);
System.out.println(date);
}catch(ParseException ex){
//exception
ex.printStackTrace();
}
Or you can add throws ParseException to your method .
According to your comment it seems to be you are trying to convert a date[String] to another format. If I am correct then the following example may help you.
String inputstring="Tue Nov 5 00:00:00 UTC+0530 2013";
SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM d HH:mm:ss zZ yyyy", Locale.ENGLISH);
DateFormat outformat = new SimpleDateFormat("dd-MMM-yy");
try {
String result = outformat.format(formatter.parse(inputstring));
System.out.println(result);
} catch (ParseException ex) {
ex.printStackTrace();
}
Output:
04-Nov-13

No Problem
Your code works* if you catch the exception as directed in the correct answer.
String input = "Tue Nov 5 00:00:00 UTC+0530 2013";
java.text.SimpleDateFormat sdformatter = new java.text.SimpleDateFormat( "EEE MMM d HH:mm:ss zZ yyyy" , Locale.ENGLISH );
java.util.Date date = null;
try {
date = sdformatter.parse( input );
} catch ( ParseException ex ) {
System.out.println( "ERROR: " + ex ); // … handle exception
}
System.out.println( "date: " + date + " (adjusted to Kolkata time via Joda-Time: " + new DateTime( date , DateTimeZone.forID( "Asia/Kolkata" ) ) );
When run.
date: Mon Nov 04 10:30:00 PST 2013 (adjusted to Kolkata time via Joda-Time: 2013-11-05T00:00:00.000+05:30
Joda-Time
That same format works in Joda-Time 2.5.
The java.util.Date/.Calendar/java.text.SimpleDateFormat classes bundled with Java are notoriously troublesome, confusing, and flawed. Avoid them. Use either Joda-Time or the new java.time package built into Java 8 (inspired by Joda-Time).
String input = "Tue Nov 5 00:00:00 UTC+0530 2013";
DateTimeFormatter formatter = DateTimeFormat.forPattern( "EEE MMM d HH:mm:ss zZ yyyy" );
DateTime dateTime = formatter.parseDateTime( input ).withZone( DateTimeZone.forID( "Asia/Kolkata" ) );
System.out.println( "dateTime: " + dateTime );
When run.
dateTime: 2013-11-05T00:00:00.000+05:30
Alternate Format
In your case, you could ignore the UTC as it is redundant with the offset ( +0530 ). An offset is assumed to be from UTC. You can ignore characters by using quote marks.
DateTimeFormatter formatter = DateTimeFormat.forPattern( "EEE MMM d HH:mm:ss 'UTC'Z yyyy" );
*Your code works for me using Java 8 Update 25. Earlier versions of java.text.SimpleDateFormat had varying behaviors with the Z-letter and offsets. But, again, you should not even be using SimpleDateFormat.

Related

Trouble formatting date in Java [duplicate]

This question already has answers here:
DateTimeParse Exception
(2 answers)
Closed 2 years ago.
I've tried several methods with Java Joda Time, Date Time with locale and commons-lang and can't get this date formatted.
Input
Mon Dec 28 15:18:16 UTC 2020
Output
Desired output format yyyy-MM-dd HH:mm:ss.SSS
When I use a format pattern like EEE MMM dd HH:mm:ss Z YYYY the date is off my a couple days and the timezone seems completely wrong.
Formatter:
private static final DateTimeFormatter DATE_TIME_FORMATTER =
DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")
.withLocale(Locale.US)
.withZone(ZoneId.systemDefault());
DateUtils.parseDate (Optional
.ofNullable(record)
.map(CustomerModel::getCustomerAudit)
.map(customerAudit::getCreated)
.map(auditItem::getDate).get ().toString (), "EEE MMM dd HH:mm:ss YYYY")
When debugging parsing issues, if possible, reverse the operation and generate the text you're supposed to be parsing, to verify the parsing rules, i.e. the date format string. This applies to date parsing, JAXB parsing, and any other (de)serializing operation that is bi-directional. It makes finding conversion rule issues a lot easier.
So, let us check the format string in the question, with the shown date value:
ZonedDateTime dateTime = ZonedDateTime.of(2020, 12, 28, 15, 18, 16, 0, ZoneOffset.UTC);
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss Z YYYY", Locale.US);
System.out.println(dateTime.format(fmt));
Output
Mon Dec 28 15:18:16 +0000 2021
Oops! That doesn't fit the expected output, aka the input we desire to parse:
Mon Dec 28 15:18:16 UTC 2020
So what went wrong?
The year is wrong because it's supposed to be uuuu (year), not YYYY (week-based-year).
The time zone is wrong because Z does support a text representation. Use VV or z instead.
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z uuuu", Locale.US);
ZonedDateTime dateTime = ZonedDateTime.parse("Mon Dec 28 15:18:16 UTC 2020", fmt);
System.out.println(dateTime);
System.out.println(dateTime.format(DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS")));
Output
2020-12-28T15:18:16Z[UTC]
2020-12-28 15:18:16.000
As you can see, it now parsed correctly.
The code in the question makes little sense:
It is formatting a Date value to text using toString(), just to attempt parsing that back.
It is using Optional for simple null-handling (which is discouraged), but then unconditionally calling get(), which means a null value will throw exception anyway.
The code should be:
record.getCustomerAudit().getCreated().getDate().toInstant()
This of course makes the entire question moot.
Works fine for me.
String s = "Mon Dec 28 15:18:16 UTC 2020";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss VV yyyy",
Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse(s, formatter);
formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS", Locale.ENGLISH);
System.out.println(zdt.format(formatter));
Output is
2020-12-28 15:18:16.000
Am I missing something?
Have you tried with SimpleDateFormat?
String dateString = "Mon Dec 28 15:18:16 UTC 2020";
SimpleDateFormat input = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.ENGLISH);
System.out.println(output.format(input.parse(dateString)));
With timezone:
String dateString = "Mon Dec 28 15:18:16 UTC 2020";
SimpleDateFormat input = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd z HH:mm:ss.SSS");
input.setTimeZone(TimeZone.getTimeZone("UTC"));
output.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(output.format(input.parse(dateString)));

How do I Date format for dd MMM yyyy, as in 01 Apr 2020 [duplicate]

This question already has answers here:
java DateTimeFormatterBuilder fails on testtime [duplicate]
(2 answers)
Closed 2 years ago.
I have a pdf file where I want to know if the next line is a date, or just a string (there are two types of formats of the listing, and knowing if I've arrived at a date is important.) The trouble is, there appears to be no way to use date formatting to arrive at a date of 01 Apr 2020
LocalDate date = parseDate( "dd MMM yyyy", "01 Apr 2020" );
Throws ... Text '01 Apr 2020' could not be parsed at index 3
private static LocalDate parseDate( final String format, final String s ) {
final DateTimeFormatter df = DateTimeFormatter.ofPattern( format );
LocalDate ld; // Check if this was a legal LocalDate.
try {
ld = LocalDate.parse(s, df);
} catch (java.time.format.DateTimeParseException pe) {
System.out.println( pe.getMessage() );
ld = null; // This will signal an error
}
return ld;
}
Is there really no way to parse that format of date, like a bank uses in their pdf?
Replace
final DateTimeFormatter df = DateTimeFormatter.ofPattern( format );
With
final DateTimeFormatter df = DateTimeFormatter.ofPattern( format , Locale.US );
Hopefully, this will resolve your issue.
I believe you're using java8, You can do
LocalDate date = LocalDate.parse("01 Apr 2020", DateTimeFormatter.ofPattern("dd MMM yyyy", Locale.ROOT));
Edited: After pointed out that it doesn't work for all locales. Locale.ROOT should be used for neutral locale.

Java how to pass the timeformat in java "Fri Jan 24 12:22:13 +0000 2014"

I have got the following created date "Fri Jan 24 12:22:13 +0000 2014" from twitter , but when it comes to parsing , the goes to unparsable exception error at "z"
Would you please tell em what is the correct time format ?
The below is my code
String dateString = fullS.substring(0, 11) + " "+ year;
String timeZoneHK = content.getTimeZone();
SimpleDateFormat inputDf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
SimpleDateFormat outputDf = new SimpleDateFormat("HH:mm:ss EEE MMM dd yyyy");
Date date;
try {
TimeZone timezone = null;
date = inputDf.parse(dateString);
if(timeZoneHK.equals("Hong Kong")){
timezone = TimeZone.getTimeZone("Asia/Hong_Kong");
}
outputDf.setTimeZone(timezone);
String result =outputDf.format(date);
//System.out.println(outputDf.format(date));
viewHolder.txtDate.setText(result);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Exception
01-24 22:10:30.061: W/System.err(12573): java.text.ParseException: Unparseable date: "Fri Jan 24 13:37:08 +0000 2014" (at offset 0)
Use complete date String "Fri Jan 24 12:22:13 +0000 2014" if wanted to apply the specified format. And change z to Z:
SimpleDateFormat inputDf = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");
Refer to: SimpleDateFormat
Z - time zone (RFC 822) - (Time Zone) Z/ZZ/ZZZ:-0800 - ZZZZ:GMT-08:00 ZZZZZ:-08:00
Joda-Time
This kind of work is much easier with the third-party open-source date-time library, Joda-Time.
Here is some example code using Joda-Time 2.3.
String input = "Fri Jan 24 12:22:13 +0000 2014";
DateTimeFormatter formatter = DateTimeFormat.forPattern( "EEE MMM dd HH:mm:ss Z yyyy" );
// Parse as UTC/GMT (no time zone offset) so we may conveniently compare to input.
DateTime dateTimeUtc = formatter.withZone( DateTimeZone.UTC ).parseDateTime( input );
// Convert to Hong Kong time zone.
DateTime dateTimeHongKong = dateTimeUtc.toDateTime( DateTimeZone.forID( "Asia/Hong_Kong" ) );
Dump to console…
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "dateTimeHongKong: " + dateTimeHongKong );
When run…
dateTimeUtc: 2014-01-24T12:22:13.000Z
dateTimeHongKong: 2014-01-24T20:22:13.000+08:00
Back To Date
If you need a java.util.Date for other purposes, convert your DateTime.
java.util.Date date = dateTime.toDate();

Converting String Format Date for Date Object

I am getting a Date format in String as Output like this.
Fri May 18 00:00:00 EDT 2012
I need to Convert this to a Date Object. What approach shall I use?
Thank you.
This is the program i used.
import java.util.*;
import java.text.*;
public class DateToString {
public static void main(String[] args) {
try {
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss 'EDT' yyyy ");
date = (Date)formatter.parse("Fri May 18 00:00:00 EDT 2012");
String s = formatter.format(date);
System.out.println("Today is " + s);
} catch (ParseException e) {
System.out.println("Exception :"+e);
}
}
}
Have a look at: java.text.SimpleDateFormat Java API
SimpleDateFormat dateParser = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy",
Locale.US);
Date date = dateParser.parse("Fri May 18 00:00:00 EDT 2012");
Update: note to self, locale can be important.
Use SimpleDateFormat and implementations to get a date displayable in a format you want.
Example:
String myDateString = "Fri May 18 00:00:00 EDT 2012";
SimpleDateFormat dateFormat = new SimpleDateFormat();
dateFormat.applyPattern( "EEE MMM dd HH:mm:ss z yyyy" );
try {
Date d = dateFormat.parse( myDateString );
System.out.println( d ); // Fri May 18 00:00:00 EDT 2012
String datePattern1 = "yyyy-MM-dd";
dateFormat.applyPattern( datePattern1 );
System.out.println( dateFormat.format( d ) ); // 2012-05-18
String datePattern2 = "yyyy.MM.dd G 'at' HH:mm:ss z";
dateFormat.applyPattern( datePattern2 );
System.out.println( dateFormat.format( d ) ); // 2012.05.18 AD at 00:00:00 EDT
String datePattern3 = "yyyy.MM.dd G 'at' HH:mm:ss Z";
dateFormat.applyPattern( datePattern3 );
System.out.println( dateFormat.format( d ) ); // 2012.05.18 AD at 00:00:00 -400
}
catch ( Exception e ) { // ParseException
e.printStackTrace();
}
Use SimpleDateFormat with the following pattern:
EEE MMM dd HH:mm:ss 'EDT' YYYY
This doesn't worry about Timezone, Alternatively, with timezone inclusion: (untested) EEE MMM dd HH:mm:ss z YYYY (it's a lowercase z). Bear in mind, I haven't tested it yet (as I'm on my way home from work).

How to parse a date? [duplicate]

This question already has answers here:
Java string to date conversion
(17 answers)
Closed 6 years ago.
I am trying to parse this date with SimpleDateFormat and it is not working:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Formaterclass {
public static void main(String[] args) throws ParseException{
String strDate = "Thu Jun 18 20:56:02 EDT 2009";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date dateStr = formatter.parse(strDate);
String formattedDate = formatter.format(dateStr);
System.out.println("yyyy-MM-dd date is ==>"+formattedDate);
Date date1 = formatter.parse(formattedDate);
formatter = new SimpleDateFormat("dd-MMM-yyyy");
formattedDate = formatter.format(date1);
System.out.println("dd-MMM-yyyy date is ==>"+formattedDate);
}
}
If I try this code with strDate="2008-10-14", I have a positive answer. What's the problem? How can I parse this format?
PS. I got this date from a jDatePicker and there is no instruction on how modify the date format I get when the user chooses a date.
You cannot expect to parse a date with a SimpleDateFormat that is set up with a different format.
To parse your "Thu Jun 18 20:56:02 EDT 2009" date string you need a SimpleDateFormat like this (roughly):
SimpleDateFormat parser=new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
Use this to parse the string into a Date, and then your other SimpleDateFormat to turn that Date into the format you want.
String input = "Thu Jun 18 20:56:02 EDT 2009";
SimpleDateFormat parser = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
Date date = parser.parse(input);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = formatter.format(date);
...
JavaDoc: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
The problem is that you have a date formatted like this:
Thu Jun 18 20:56:02 EDT 2009
But are using a SimpleDateFormat that is:
yyyy-MM-dd
The two formats don't agree. You need to construct a SimpleDateFormat that matches the layout of the string you're trying to parse into a Date. Lining things up to make it easy to see, you want a SimpleDateFormat like this:
EEE MMM dd HH:mm:ss zzz yyyy
Thu Jun 18 20:56:02 EDT 2009
Check the JavaDoc page I linked to and see how the characters are used.
We now have a more modern way to do this work.
java.time
The java.time framework is bundled with Java 8 and later. See Tutorial. These new classes are inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. They are a vast improvement over the troublesome old classes, java.util.Date/.Calendar et al.
Note that the 3-4 letter codes like EDT are neither standardized nor unique. Avoid them whenever possible. Learn to use ISO 8601 standard formats instead. The java.time framework may take a stab at translating, but many of the commonly used codes have duplicate values.
By the way, note how java.time by default generates strings using the ISO 8601 formats but extended by appending the name of the time zone in brackets.
String input = "Thu Jun 18 20:56:02 EDT 2009";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "EEE MMM d HH:mm:ss zzz yyyy" , Locale.ENGLISH );
ZonedDateTime zdt = formatter.parse ( input , ZonedDateTime :: from );
Dump to console.
System.out.println ( "zdt : " + zdt );
When run.
zdt : 2009-06-18T20:56:02-04:00[America/New_York]
Adjust Time Zone
For fun let's adjust to the India time zone.
ZonedDateTime zdtKolkata = zdt.withZoneSameInstant ( ZoneId.of ( "Asia/Kolkata" ) );
zdtKolkata : 2009-06-19T06:26:02+05:30[Asia/Kolkata]
Convert to j.u.Date
If you really need a java.util.Date object for use with classes not yet updated to the java.time types, convert. Note that you are losing the assigned time zone, but have the same moment automatically adjusted to UTC.
java.util.Date date = java.util.Date.from( zdt.toInstant() );
How about getSelectedDate? Anyway, specifically on your code question, the problem is with this line:
new SimpleDateFormat("yyyy-MM-dd");
The string that goes in the constructor has to match the format of the date. The documentation for how to do that is here. Looks like you need something close to "EEE MMM d HH:mm:ss zzz yyyy"
In response to:
"How to convert Tue Sep 13 2016 00:00:00 GMT-0500 (Hora de verano central (México)) to dd-MM-yy in Java?", it was marked how duplicate
Try this:
With java.util.Date, java.text.SimpleDateFormat, it's a simple solution.
public static void main(String[] args) throws ParseException {
String fecha = "Tue Sep 13 2016 00:00:00 GMT-0500 (Hora de verano central (México))";
Date f = new Date(fecha);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.setTimeZone(TimeZone.getTimeZone("-5GMT"));
fecha = sdf.format(f);
System.out.println(fecha);
}

Categories