Android Date Format Convert Eror APP - java

SimpleDateFormat formatter = new SimpleDateFormat(“EEE MMM dd HH:mm:ss zzz yyyy”);
Date date= null ;
date = formatter.parse(String.valueOf(m.getSentDate()));
formatter = new SimpleDateFormat(“dd.MM.yyyy”);
tarih=formatter.format(date);
ERROR = “java.text.ParseException: Unparseable date: “Wed Jan 20 15:13:09 EET 2016″ (at offset 0)”
I get this error code permanently
java mail api from history= Mon jan 18 21:17:31 ETT 2016
I want to convert methods = 18.01.2016 21:17:31
I'm sorry my bad english

Your formatter should be working. So something else is wrong.
Here is my example code using your formatter and your input string.
String input = "Wed Jan 20 15:13:09 EET 2016";
SimpleDateFormat formatter = new SimpleDateFormat ( "EEE MMM dd HH:mm:ss zzz yyyy" );
Date date = null;
try {
date = formatter.parse ( input );
} catch ( ParseException e ) {
System.out.println ( "Exception… " + e );
}
System.out.println ( "date: " + date + " | date via formatter: " + formatter.format ( date ) + " | as Instant: " + date.toInstant () );
When run.
date: Wed Jan 20 05:13:09 PST 2016 | date via formatter: Wed Jan 20 15:13:09 EET 2016 | as Instant: 2016-01-20T13:13:09Z
Curly-Quotes
I am seeing many curly-quotes in your code and output. Hopefully those are not in the original. Curly quotes are typographically nice but inappropriate in programming code.
If you are using word-processors for your programming, stop that. They are not built for programming and will inject these curly-quotes among many other problems. Learn to use text editors intended for programming source code.
java.time
By the way, the old java.util.Date/.Calendar classes are notoriously troublesome. They have been supplanted in Java 8 and later by the new built-in java.time framework.

Related

java SimpleDateFormat? [duplicate]

This question already has answers here:
Parsing SimpleDateFormat
(2 answers)
Closed 6 years ago.
public static void main(String[] args) {
Date now = new Date();
String dateString = now.toString();
System.out.println(" 1. " + dateString);
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
try {
Date parsed = format.parse(dateString);
System.out.println(" 2. " + parsed.toString());
} catch (ParseException pe) {
System.out.println("ERROR: Cannot parse \"" + dateString + "\"");
}
System.out.println(" 3. " + format.format(now));
}
print in console:
1. Thu Feb 23 17:14:51 CET 2017
ERROR: Cannot parse "Thu Feb 23 17:14:51 CET 2017"
3. jeu. févr. 23 05:14:51 CET 2017
instead of:
1. Thu Feb 23 17:14:51 CET 2017
2. Thu Feb 23 17:14:51 CET 2017
3. jeu. févr. 23 05:14:51 CET 2017
It looks like your default Locale is FRENCH, and since SimpleDateFormat uses it if you don't specify another one, you can't successfully parse english abreviations like Thu or Feb.
However, you can specify the use of the ENGLISH Locale like this:
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
You have run into one of the many diseases of the now out-dated Date class in Java.
The sound and easy fix is to change over to the Java 8 date and time classes. The new class that best corresponds to Date is Instant. With this class your code becomes:
Instant now = Instant.now();
String dateString = now.toString();
System.out.println(" 1. " + dateString);
try {
Instant parsed = Instant.parse(dateString);
System.out.println(" 2. " + parsed.toString());
} catch (DateTimeParseException e) {
System.out.println("ERROR: Cannot parse \"" + dateString + "\"");
}
I have left out 3. from your example. Of course it is possible to format the Instant in about any way you could dream of, but if we just want the same output as from the toString method I don’t find it worth it for now. Rather I would like to show that for this case you don’t need a format at all. The code prints:
1. 2017-02-23T17:07:19.775Z
2. 2017-02-23T17:07:19.775Z
You notice that it prints the time in UTC. If you want your local time zone instead, just use ZonedDateTime instead of Instant. The rest of the code is exactly the same, but now output on my computer is:
1. 2017-02-23T18:07:19.852+01:00[Europe/Berlin]
2. 2017-02-23T18:07:19.852+01:00[Europe/Berlin]
Of course it is possible to generate an error like the one you get from disagreeing locales also with the new classes. As far as I can see, you would have to explicitly specify disagreeing locales. So you don’t do it easily.

Formatting date with time zone. Wrong format

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.

Simple date format in IST and KST

I use the following simple date format to parse a string,
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
String time = "Wed Mar 06 21:00:00 IST 2014";
Date date = dateFormat.parse(time);
This throws no error whreas,
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
String time = "Wed Mar 06 21:00:00 KST 2014";
Date date = dateFormat.parse(time);
Throws unparseable date exception.
where,
IST - Indian standard time
*KST - korean standard time*
I have decided to remove time zone because of the exception.
Is there any other way to work around this issue?
Please help
Avoid Time Zone Codes
Avoid those 3 or 4 letter codes for time zones. They are neither standardized nor unique. For example, the IST you cite as "Indian Standard Time" is also "Irish Standard Time". Plus they are confusing when in fact you may mean "Summer Time"/"Daylight Saving Time". Instead use proper time zone names, usually made up of a country plus primary city.
Use Sensible Formats For Date-Time Strings
That format "Wed Mar Thu 21:00:00 IST 2014" is not good. Besides being wrong (looks like you typed "Wed" or "Thu" where you should have a day-of-month number), it uses the 3-4 letter code, contains superfluous data (day of week), and assumes English readers. When moving date-time values around as text, use the sensible ISO 8601 format: YYYY-MM-DDTHH:MM:SS.sssZ such as 2014-03-04T23:20:28Z.
If changing that format is out of your control, you'll have to determine all the possible 3-4 letter codes that may be used in your data sets and see if your date-time library can handle them.
Avoid java.util.Date/Calendar
The java.util.Date and .Calendar classes are notoriously troublesome. They are outmoded as of Java 8 with the new java.time package. That package is based on the Joda-Time library. Use either Joda-Time or java.time.
Joda-Time
Note that in contrast to java.util.Date, a Joda-Time DateTime object truly knows its assigned time zone.
Here's some Joda-Time 2.3 example code.
String inputIso = "2014-03-19T21:00:00+05:30";
DateTimeZone timeZoneIndia = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeIndia = new DateTime( inputIso, timeZoneIndia );
// Adjust to Korea Time.
DateTimeZone timeZoneKorea = DateTimeZone.forID( "Asia/Seoul" );
DateTime dateTimeKorea = dateTimeIndia.withZone( timeZoneKorea );
// Adjust to UTC (GMT).
DateTime dateTimeUtc = dateTimeKorea.withZone( DateTimeZone.UTC );
String inputLame = "Thu Mar 20 21:00:00 KST 2014";
DateTimeZone timeZone = null;
if( inputLame.contains( "IST" )) { // Assume IST = India time.
timeZone = DateTimeZone.forID( "Asia/India" );
inputLame = inputLame.replace( " IST ", " ");
}
if( inputLame.contains( "KST" )) { // Assume KST = Korea time.
timeZone = DateTimeZone.forID( "Asia/Seoul" );
inputLame = inputLame.replace( " KST ", " ");
}
DateTimeFormatter formatter = DateTimeFormat.forPattern( "EEE MMM dd HH:mm:ss yyyy" ).withZone( timeZone ).withLocale( java.util.Locale.ENGLISH );
DateTime dateTimeLame = formatter.parseDateTime( inputLame );
Dump to console…
System.out.println( "dateTimeIndia: " + dateTimeIndia );
System.out.println( "dateTimeKorea: " + dateTimeKorea );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "dateTimeLame: " + dateTimeLame );
When run…
dateTimeIndia: 2014-03-19T21:00:00.000+05:30
dateTimeKorea: 2014-03-20T00:30:00.000+09:00
dateTimeUtc: 2014-03-19T15:30:00.000Z
dateTimeLame: 2014-03-20T21:00:00.000+09:00
Both the dates are invalid, hence both would throw the error:
String time = "Wed Mar Thu 21:00:00 IST 2014";
Thu is invalid as the day of the week is already consumed by EEE - Wed combination. You need to set a day of the month there.
Try parsing the following date, it should work for your case:
String time = "Wed Mar 12 21:00:00 KST 2014";
Try this piece of code and see if KST is a valid time zone id
String[] timezoneIdArr = TimeZone.getAvailableIDs();
for (String tzId : timezoneIdArr) {
System.out.println(tzId);
}
If not, then enter zone id like "Asia/Seoul" or something. That should work.
Please note that I have not tried it. Please check exact spellings of the time zones.
Update:
Try the code below. See what KST yields. Uncomment and try with Asia/Seoul. For your reference, uncomment and see how PST works.
private static void calTest() {
String zone = "KST";
//String zone = "Asia/Seoul";
//String zone = "PST";
long millis = System.currentTimeMillis();
//get calendar of Korea time zone.
Calendar kst = Calendar.getInstance(TimeZone.getTimeZone(zone));
//set its time to a UTC millisecond value. probably redundant, but just to demonstrate
kst.setTimeInMillis(millis);
String formattedKst = formatTime(kst);
System.out.println(" Original - " + formattedKst);
//now we convert the formatted string back to a Calendar .
Calendar parsedKst = parseTime(formattedKst, zone);
System.out.println(" Parsed - ");
System.out.println("" + parsedKst.get(Calendar.YEAR) + "-"
+ (parsedKst.get(Calendar.MONTH) + 1) + "-"
+ parsedKst.get(Calendar.DATE) + " "
+ parsedKst.get(Calendar.HOUR_OF_DAY) + ":"
+ parsedKst.get(Calendar.MINUTE) + ":"
+ parsedKst.get(Calendar.SECOND) + "."
+ parsedKst.get(Calendar.MILLISECOND) + " "
+ parsedKst.getTimeZone().getID() + " "
+ parsedKst.getTimeZone().getDisplayName() + " "
);
}
private static Calendar parseTime(String formattedDateTime, String ID) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX zzz");
sdf.setTimeZone(TimeZone.getTimeZone(ID));
sdf.setLenient(false);
try {
sdf.parse(formattedDateTime);
} catch (ParseException e) {
e.printStackTrace();
}
return sdf.getCalendar();
}
private static String formatTime(Calendar cal) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX zzz");
sdf.setCalendar(cal);
return sdf.format(cal.getTime());
}

how to convert date in java

I am new in android .
I have to convert following date into this time stamp (Wed Oct 12 14:17:42 GMT+05:30 2011)
Thu, 27 May 2010 12:37:27 GMT
This is the date that I am getting from the server through the header. I have converted it into the String object. Now I have to convert it into the Date format like: Wed Oct 12 14:17:42 GMT+05:30 2011
Please could you help me how should I convert it into the (Wed Oct 12 14:17:42 GMT+05:30 2011) this format using timestamp.
Have a look at DateFormat or SimpleDateFormat which provide parse() and format() methods. DateFormat provides a bunch of standard formats whereas SimpleDateFormat allows you to provide your own format expression.
Example for your input date:
//note that you need the locale as well, since the weekdays and months are written in a specific language, English in that case
SimpleDateFormat parseFormat = new SimpleDateFormat( "E, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH );
SimpleDateFormat writeFormat = new SimpleDateFormat( "E MMM dd HH:mm:ss z yyyy", Locale.ENGLISH );
writeFormat.setTimeZone( TimeZone.getTimeZone( "GMT" ) );
Date tDate = parseFormat.parse( "Wed, 12 Oct 2011 14:17:42 GMT" );
System.out.println(writeFormat.format(tDate )); //Wed Oct 12 14:17:42 GMT 2011
Edit: If you want a more usable API, try JodaTime.

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