I got a date time format - "dd MMM yyyy", when trying to parse "6 Aug 2012", I get an java.text.ParseException Unparseable date.
Every thing looks fine, do you see the problem?
You need to mention the Locale as well...
Date date = new SimpleDateFormat("dd MMMM yyyy", Locale.ENGLISH).parse("6 Aug 2012");
Use something like:
DateFormat sdf = new SimpleDateFormat("dd MMM yyyy", Locale.ENGLISH);
Date date = sdf.parse("6 Aug 2012");
Use the split() function with the delimiter " "
String s = “6 Aug 2012”;
String[] arr = s.split(" ");
int day = Integer.parseInt(arr[0]);
String month = arr[1];
int year = Integer.parseInt(arr[2]);
This should work for you. You will need to provide a locale
Date date = new SimpleDateFormat("dd MMM yyyy", Locale.ENGLISH).parse("6 Aug 2012");
Or
Date date = new SimpleDateFormat("dd MMM yyyy", new Locale("EN")).parse("6 Aug 2012");
While the other answers are correct but outdated and since this question is still being visited, here is the modern answer.
java.time and ThreeTenABP
Use java.time, the modern Java date and time API, for your date work. This will work with your Android version/minSDK:
DateTimeFormatter dateFormatter
= DateTimeFormatter.ofPattern("d MMM uuuu", Locale.ENGLISH);
String str = "6 Aug 2012";
LocalDate date = LocalDate.parse(str, dateFormatter);
System.out.println(date);
Output:
2012-08-06
In the format pattern java.time uses just one d for either one or two digit day of month. For year you may use either of yyyy, uuuu, y and u. And as the others have said, specify locale. If Aug is English, then an English-speaking locale.
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Similar question to this one: Java - Unparseable date.
Oracle tutorial: Date Time explaining how to use java.time.
Question: uuuu versus yyyy in DateTimeFormatter formatting pattern codes in Java?
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Related
how to I convert date time to others time zone using java.
example : 11 June 2021 20:00 to 11 June 2021 06:00 PM
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date parsed = format.parse("2021-03-01 20:00");
*\\to//*
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm z");
Date parsed = format.parse("2021-03-01 06:00 PM");
like this
First of all you should use the new java 8 API for data and time, java.time, secondly you need to have a zone to convert to and from. Here I have assumed you want to use the zone of the device (and convert to GMT) as from and GMT as to.
String input = "2021-03-01 20:00";
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").withZone(ZoneId.systemDefault());
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd h:mm a").withZone(ZoneId.of("GMT"));
TemporalAccessor date = inputFormatter.parse(input);
String output = outputFormatter.format(date);
System.out.println(output);
Joakim Danielson is on to the right thing in his answer: use java.time, the modern Java date and time API, for your date and time work. My solution roughly follows the same overall pattern. There are some details I’d like to show you.
private static final DateTimeFormatter inputFormatter
= DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
private static final DateTimeFormatter outputFormatter
= DateTimeFormatter.ofPattern("yyyy-MM-dd h:mm a");
DateTimeFormatter is thread-safe so there’s no problem instantiating them only once even if they are used from different threads.
String input = "2021-03-01 20:00";
String output = LocalDateTime.parse(input, inputFormatter)
.atZone(ZoneId.systemDefault())
.withZoneSameInstant(ZoneOffset.UTC)
.format(outputFormatter);
System.out.println(output);
Output is the same as from Joakim’s code. In my time zone (Europe/Copenhagen) it is:
2021-03-01 7:00 PM
java.time lends itself well to a fluent writing style. Why not exploit it? Since conversion to a different time zone was the point, I prefer to make it explicit in the code. The withZoneSameInstant() call makes the conversion. And I prefer to parse into either LocalDateTime or ZonedDateTime rather than using the low-level TemporalAccessor interface directly. The documentation of the interface says:
This interface is a framework-level interface that should not be
widely used in application code. Instead, applications should create
and pass around instances of concrete types, such as LocalDate.
There are many reasons for this, part of which is that implementations
of this interface may be in calendar systems other than ISO. …
I need api 21 support. This is not available on api 21
Indeed java.time works nicely on Android API level 21.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On older Android either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Documentation of TemporalAccessor
Question: cannot resolve symbol 'java.time.LocalDate' error in android studio about using java.time on earlier Andoird
Question: Android - Date in API Level 21 [closed]
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
Java 8+ APIs available through desugaring
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
You must get your date format to a specific zone, as you have not mentioned in the post, i will give 1 sample below,
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(yyyy-MM-dd HH:mm);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Now using this simpleDateFormat for your specific timezone, you can format the value.
The key to the solution is to get the zone offset between two date-times which you can calculate with Duration#between and then change the zone offset of the first date-time into that of the second one (which is equal to the hours and minutes part of the calculated duration.
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Given date-time strings
String strOne = "11 June 2021 20:00";
String strTwo = "11 June 2021 06:00 PM";
// Respective formatters
DateTimeFormatter dtfOne = DateTimeFormatter.ofPattern("dd MMMM uuuu HH:mm", Locale.ENGLISH);
DateTimeFormatter dtfTwo = DateTimeFormatter.ofPattern("dd MMMM uuuu hh:mm a", Locale.ENGLISH);
// Respective instances of LocalDateTime
LocalDateTime ldtOne = LocalDateTime.parse(strOne, dtfOne);
LocalDateTime ldtTwo = LocalDateTime.parse(strTwo, dtfTwo);
// Duration between the two date-times
Duration duration = Duration.between(ldtOne, ldtTwo);
int hours = duration.toHoursPart();
int minutes = duration.toMinutesPart();
// Zone offset with hours and minutes of the duration
ZoneOffset zoneOffset = ZoneOffset.ofHoursMinutes(hours, minutes);
//
ZonedDateTime zdt = ldtOne.atZone(ZoneId.systemDefault()) // ZonedDateTime using JVM's time zone
.withZoneSameInstant(zoneOffset); // ZonedDateTime using the given zone offset
System.out.println(zdt);
String formatted = zdt.format(dtfTwo);// Format the given ZonedDateTime using the given formatter
System.out.println(formatted);
}
}
The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API. Learn more about the modern date-time API at Trail: Date Time.
Note: If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
This question already has answers here:
Java - Unparseable date
(3 answers)
Getting error java.text.ParseException: Unparseable date: (at offset 0) even if the Simple date format and string value are identical
(4 answers)
Closed 4 years ago.
I am trying to parse the following date/time:
Wed, 29 Aug 2018 12:56:00 +0200
Currently, I am using the following code which works on my Android emulator but on my actual phone I get a "java.text.ParseException: Unparseable date"
SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
this.pubDate = sdf.parse(s_pubDate);
You need to explicitly set the formatter locale, otherwise it would try to pars it based on phone locale and that may cause an error. I think that the cause in your case.
Your emulated device has one locale, while your phone has the one, that can't pars date in such format.
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z",
**YOUR DESIRED LOCALE**);
java.time
String dateTimeString = "Wed, 29 Aug 2018 12:56:00 +0200";
OffsetDateTime dateTime = OffsetDateTime.parse(
dateTimeString, DateTimeFormatter.RFC_1123_DATE_TIME);
System.out.println(dateTime);
Output from this snippet is:
2018-08-29T12:56+02:00
The format of the string you want to parse is RFC 1123. This format is built into Java, so spares you the trouble of building your own formatter for parsing. Furthermore RFC 1123 is always in English, so there is no risk that your phone’s default locale (or any other locale) interferes.
I am using java.time, the modern Java date and time API. The SimpleDateFormat that you tried to use is not only long outdated, it is also notoriously troublesome.
Question: Can I use java.time on Android?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26, I’m told) the modern API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
I am working on server and server is sending me date on GMT Local Date like Fri Jun 22 09:29:29 NPT 2018 on String format and I convert it into Date like below:
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy",Locale.English);
Date newDate=simpleDateFormat.parse("Fri Jun 22 09:29:29 NPT 2018");
TimeAgo ta=new TimeAgo();
Log.d(TAG,""+ta.timeAgo(newDate));
What I need is take out the Time in Ago like 5 hours ago for that I use the one github project on which returns TimeAgo on passing date.
I have already look at this answer but didn't solve my problem.
Exception: Err java.text.ParseException: Unparseable date: "Fri Jun 22 09:29:29 NPT 2018" (at offset 20)
Err java.text.ParseException: Unparseable date: "Fri Jun 22 09:29:29 NPT 2018" (at offset 20)
NPT is not recognized as a time zone abbreviation
The parsing of your date-time string (apparently the output from Date.toString()) is the problem (not the subsequent use of TimeAgo, which you could have left out from the question to make it clearer). The unparseable part is at index 20, that is where it says NPT, which I take to mean Nepal Time. So SimpleDateFormat on your Android device or emulator doesn’t recognize NPT as a time zone abbreviation.
Time zone abbreviations come as part of the locale data. I am not an Android developer and don’t know from where Android gets its locale data. A fast web search mentioned ICU and CLDR. You can search more thoroughly and no doubt find information I didn’t find.
I am presenting three suggestions for you to try. I admit at once that the first two are unlikely to solve your problem, but I nevertheless find them worth trying. And I promise that the third will work if the first two don’t.
1. Use ThreeTenABP and java.time
I agree with the answer by notyou that the classes Date and SimpleDateFormat are outmoded and that it’s better to use java.time, the modern Java date and time API. Can you do that on Android prior to Android O? Yes, most of java.time has been backported. The Android edition of the backport is called ThreeTenABP. Use the links at the bottom. Then try:
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ROOT);
ZonedDateTime newDateTime
= ZonedDateTime.parse("Fri Jun 22 09:29:29 NPT 2018", formatter);
System.out.println(newDateTime);
Make sure you use the imports for the backport:
import org.threeten.bp.ZonedDateTime;
import org.threeten.bp.format.DateTimeFormatter;
I have tested with the same backport, only not the Android edition. I got:
2018-06-22T09:29:29+05:45[Asia/Kathmandu]
I suspect that ThreeTenABP uses the same locale data, though, and if so, this doesn’t solve your problem.
2. Set the time zone on the formatter
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ROOT)
.withZone(ZoneId.of("Asia/Kathmandu"));
If it works, I find it straightforward and clean. If you insist on using SimpleDateFormat, you can try a similar trick with it. I get the same output as above.
3. Handle NPT as literal text
This is a hack: require that the three letters NPT occur in the string without interpreting them as a time zone. This eliminates the need for the abbreviation to be recognized as a time zone, so will work.
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("EEE MMM dd HH:mm:ss 'NPT' yyyy", Locale.ROOT)
.withZone(ZoneId.of("Asia/Kathmandu"));
We also need to set the time zone since this is now the only place Java can get the time zone from.
But TimeAgo requires a Date
To obtain an old-fashioned Date object for TimeAgo, convert like this:
Date newDate = DateTimeUtils.toDate(newDateTime.toInstant());
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.timeto Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
The Date class is predominantly deprecated, so I would suggest not to use that.
Perhaps consider using something like the ZonedDateTime class for your problem.
If you're just looking for 5 hours before the String sent over to you, you could use something like:
String time = "Fri Jun 22 09:29:29 NPT 2018";
DateTimeFormatter format = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz uuuu");
ZonedDateTime zdt = ZonedDateTime.parse(time, format);
System.out.println(zdt.minusHours(5));
I tried the below code but it gives me the name of the day of week two days ago.
DatePicker picker;
int date = picker.DayOfMonth;
int month = (picker.Month + 1);//month is 0 based
int year = picker.Year;
SimpleDateFormat simpledateformat = new SimpleDateFormat("EEE");
Date dt = new Date(year, month, date);
First convert your Date in to specific Date format using SimpleDateFormat
Use SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE"); to get Day name in week
WHERE EEEE -> Day name in week
SAMPLE CODE
SimpleDateFormat inFormat = new SimpleDateFormat("dd-MM-yyyy");
try {
Date myDate = inFormat.parse(date+"-"+month+"-"+year);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
String dayName=simpleDateFormat.format(myDate);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE", Locale.US);
String asWeek = dateFormat.format(dt);
DateTimeFormatter dayOfWeekFormatter
= DateTimeFormatter.ofPattern("EEE", Locale.ENGLISH);
LocalDate date = LocalDate.of(
picker.getYear(), picker.getMonth(), picker.getDayOfMonth());
System.out.println(date.format(dayOfWeekFormatter));
Picking 2018-04-09 this printed
Mon
I am using and recommending java.time, the modern Java date and time API. The Date class is long outdated, and you are using a deprecated constructor. It was deprecated because it works unreliably across time zones, so you shouldn’t. SimpleDateFormat is not only outdated, it is also notoriously troublesome. I recommend you avoid those classes altogether. The modern API is so much nicer to work with.
What went wrong in your code?
You’ve got two bugs apart from using the deprecated Date constructor and the outdated classes:
It’s the Date’s month that is 0-based (not that of DatePicker), so you need to subtract 1, not add 1 (or maybe they are both 0-based??).
The deprecated Date constructor’s year is “1900-based”. This may have seemed a good idea when the class was designed in the 1990’s: you could just specify 95 to get 1995. When you pass 2018 to the constructor, you get year 3918. That’s right. :-(
Question: Can I use java.time on Android?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26, I’m told) the modern API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.timeto Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Calendar calendar = Calendar.getInstance();
DateFormat date4= new SimpleDateFormat("EEEE", Locale.getDefault());
String localTime4 = date4.format(calendar.getTime());
Simple and easy way
just use this
I am getting the above exception while trying to parse. I tried the following date format,
SimpleDateFormat sdf = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss ", Locale.ENGLISH);
java.time
The SimpleDateFormat class is not only long outdated, it is also notoriously troublesome. I recommend you stop using it and use java.time the modern Java date and time API also known as JSR-310, instead. It is so much nicer to work with.
System.out.println(LocalDateTime.parse("Thu, 7 Dec 2017 07:40:40 ",
DateTimeFormatter.ofPattern("E, d MMM yyyy HH:mm:ss ", Locale.ENGLISH)));
This prints the expected date and time:
2017-12-07T07:40:40
What went wrong
In your format pattern string, you’ve got two spaces before and two spaces after yyyy, where it seems that in your date-time string there is only one space in each of those places. While SimpleDateFormat is infamous for parsing strings that it ought to reject, it does object in this case by throwing the ParseException the message of which you quote in the question title.
If you compare my format pattern string to yours, you will notice I use just one d where you use two. SimpleDateFormat parses 7 with dd where the modern classes are stricter: d matches a date-of-month of either 1 or 2 digits. where dd requires two digits. You may of course exploit this for stricter validation if you need it.
Question: Can I use the modern API with my Java version?
If using at least Java 6, you can.
In Java 8 and later the new API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310).
On Android, use the Android edition of ThreeTen Backport. It’s called ThreeTenABP, and there’s a thorough explanation in this question: How to use ThreeTenABP in Android Project.
For learning to use java.time, see the Oracle tutorial or find other resoureces on the net.
it seems working fine with space as well...what exception you get?
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class SimpleDateFormatExample {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss ",Locale.ENGLISH);
String strDate= sdf.format(new Date());
System.out.println(strDate);
}
}
Ouput:Fri, 08 Dec 2017 07:54:08