I have the String 11/08/2013 08:48:10
and i use SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
and when im parsing it throws an exception : unparseable date
what's wrong with it ?
String result = han.ExecuteUrl("http://"+han.IP+":8015/api/Values/GetLastChange");
Log.d("Dal","result date time "+result); #result is 11/08/2013 08:48:10
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date convertedDate = new Date();
try
{
convertedDate = dateFormat.parse(result);
}
catch (ParseException e)
{
e.printStackTrace();
}
Its working try parse your date like this..
String dtStart = "11/08/2013 08:48:10";
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
try {
date = format.parse(dtStart);
System.out.println("Date ->" + date);
} catch (ParseException e) {
e.printStackTrace();
}
Working code is here.
You can use below code to convert from String to Date
String myStrDate = "11/08/2013 08:48:10";
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
try {
Date date = format.parse(myStrDate);
System.out.println(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
For reverse, it means, to convert from Date to String
SimpleDateFormat myFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
try {
Date date = new Date();
String datetime = myFormat.format(date);
System.out.println("Current Date Time in give format: " + datetime);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
For more reference, regarding Date and Time formatting. Visit developer site
java.time and ThreeTenABP
It’s not the answer that you asked for, but it should be the answer that other readers want in 2020 and onward.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/uuuu HH:mm:ss");
String result = "11/08/2013 08:48:10";
LocalDateTime dateTime = LocalDateTime.parse(result, formatter);
System.out.println("Parsed date and time: " + dateTime);
Output from this snippet is:
Parsed date and time: 2013-11-08T08:48:10
The Date class that you used is poorly designed and long outdated, so don’t use that anymore. Instead I am using java.time, the modern Java date and time API. If you need a Date for a legacy API that you cannot afford to upgrade just now, the conversion is:
Instant i = dateTime.atZone(ZoneId.systemDefault()).toInstant();
Date oldfashionedDate = DateTimeUtils.toDate(i);
System.out.println("Converted to old-fashioned Date: " + oldfashionedDate);
Converted to old-fashioned Date: Fri Nov 08 08:48:10 CET 2013
What went wrong in your code?
what's wrong with it ?
The only thing wrong with your code is you’re using the notoriously troublesome SimpleDateFOrmat and the poorly designed Date class. Which wasn’t wrong when you asked the question in 2013. java.time didn’t come out until 4 months later.
Your code is running fine. One may speculate that a leading space or the like in your string has prevented parsing. If this was the problem, try parsing result.trim() rather than just result since trim() returns a string with the leading and trailing whitespace removed.
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. Only in this case the conversion to Date is a little simpler: Date.from(i).
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
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.
Related
I am having a method which formats my particular data string
public static String dateFormatter(String dateToFormat){
SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd", Locale.UK);
// All the fields in dateFormatter must be in dateParser
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy, MMM d, EEE", Locale.UK);
Date date = new Date();
try {
date = dateParser.parse(dateToFormat);
} catch (ParseException e) {
e.printStackTrace();
}
assert date != null;
return dateFormatter.format(date);
}
The issue am having is that the String date am parsing as dateToFormat can be in the following date format pattern
2021-03-02 which will use date format pattern of "yyyy-MM-dd" in dateParser
2021-03-02 20:16 which will use date format pattern of "yyyy-MM-dd HH:mm" in dateParser
2021-03-02 20:16:28 which will use date format pattern of "yyyy-MM-dd HH:mm:ss" in dateParser
I would like the dateParser to be assigned with an if statement instead of me going back to the code
everytime to change so that the dateParser uses a particular format according to the date parsed for example
SimpleDateFormat dateParser;
if ("yyyy-MM-dd"){
dateParser = new SimpleDateFormat("yyyy-MM-dd", Locale.UK);
}else if ("yyyy-MM-dd HH:mm") {
dateParser = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.UK);
}else if ("yyyy-MM-dd HH:mm:ss") {
dateParser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.UK);
}
Where "yyyy-MM-dd" and "yyyy-MM-dd HH:mm" is the format pattern of the parsed String dateToFormat
Create 3 defferent formatter for yyyy-MM-dd, yyyy-MM-dd HH:mm, yyyy-MM-dd HH:mm:ss respectively formatter1, formatter2, formatter3
private String dateFormatter(String dateToFormat) {
Date date = null;
SimpleDateFormat formatter1=new SimpleDateFormat("yyyy-MM-dd", Locale.UK);
SimpleDateFormat formatter2=new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.UK);
SimpleDateFormat formatter3=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.UK);
try {
try {
date = formatter1.parse(dateToFormat);
} catch (
Exception exp) {
try {
date = formatter2.parse(dateToFormat);
} catch (Exception exp2) {
try {
date = formatter3.parse(dateToFormat);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy, MMM d, EEE", Locale.UK);
return dateFormatter.format(date);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
java.time and optional parts of the format pattern
Consider using java.time, the modern Java date and time API, for your date work. The following method does it. Since with java.time there is no reason to create the formatters anew for each call, I have placed them outside the method.
private static final DateTimeFormatter inputParser
= DateTimeFormatter.ofPattern("uuuu-MM-dd[ HH:mm[:ss]]");
private static final DateTimeFormatter outputFormatter
= DateTimeFormatter.ofPattern("uuuu, MMM d, EEE", Locale.UK);
public static String dateFormatter(String dateToFormat){
LocalDate date = LocalDate.parse(dateToFormat, inputParser);
return date.format(outputFormatter);
}
Try it out:
System.out.println("2021-03-02 -> " + dateFormatter("2021-03-02"));
System.out.println("2021-03-02 20:16 -> " + dateFormatter("2021-03-02 20:16"));
System.out.println("2021-03-02 20:16:28 -> " + dateFormatter("2021-03-02 20:16:28"));
Output is:
2021-03-02 -> 2021, Mar 2, Tue
2021-03-02 20:16 -> 2021, Mar 2, Tue
2021-03-02 20:16:28 -> 2021, Mar 2, Tue
The square brackets in the format pattern string for the input parser denote optional parts. So the time of day is allowed to be there or not. And if it’s there, the seconds are allowed to be present or absent.
This said, you should not want to process your date and time as strings in your app. Process a LocalDate, or if there’s any possibility that you will need the time of day, then for example a ZonedDateTime. When you get string input, parse it first thing. And only format back into a string when you must give string output.
With if statements
can your find a way that i can use SimpleDateFormat
I would not want to do that. The SimpleDateFormat class is a notorious troublemaker of a class and fortunately long outdated
I there a way i can only use if statements so that i don't get to use
many SimpleDateFormats
It doesn’t get you fewer formatters, but you may use if statements. Just select by the length of the string;
public static String dateFormatter(String dateToFormat){
LocalDate date;
if (dateToFormat.length() == 10) { // uuuu-MM-dd
date = LocalDate.parse(dateToFormat, dateParser);
} else if (dateToFormat.length() == 16) { // uuuu-MM-dd HH:mm
date = LocalDate.parse(dateToFormat, dateTimeNoSecsParser);
} else if (dateToFormat.length() == 19) { // uuuu-MM-dd HH:mm:ss
date = LocalDate.parse(dateToFormat, dateTimeWithSecsParser);
} else {
throw new IllegalArgumentException("Unsupported length " + dateToFormat.length());
}
return date.format(outputFormatter);
}
Only now we need to declare four formatters, three for parsing and one for formatting. I am leaving constructing the parsers to yourself.
I guess that the same if-else strucure will work with SimpleDateFormat too. You may even just select the format pattern string from the length of the input string and only construct one SimpleDateFormat instance in each call of the method. I repeat: I would not myself use SimpleDateformat.
Question: Doesn’t java.time require Android API level 26?
Call requires API level 26 (current min is 16):
java.time.format.DateTimeFormatter#ofPattern
Edit: Contrary to what you might think from this error message 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 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.
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.
This question already has answers here:
Converting ISO 8601-compliant String to java.util.Date
(31 answers)
Closed 4 years ago.
How do I can parse this date 2018-01-09T11:11:02.0+03:00 to dd.MM.yyyy hh:mm format in Android?
And what does T between 09 and 11 mean?
Thanks.
I don't know how the back-end developer got this format.
I am using Java.
You can do this with SimpleDateFormat.
Here is a tested example in Java:
String dateString = "2018-01-09T11:11:02.0+03:00";
String inPattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
String outPattern = "dd.MM.yyyy hh:mm";
SimpleDateFormat inFormat = new SimpleDateFormat(inPattern, Locale.getDefault());
SimpleDateFormat outFormat = new SimpleDateFormat(outPattern, Locale.getDefault());
try {
Date inDate = inFormat.parse(dateString);
String outDate = outFormat.format(inDate);
Log.e("TEST", outDate);
} catch (ParseException e) {
e.printStackTrace();
}
Here is a tested example in Kotlin:
val dateString = "2018-01-09T11:11:02.0+03:00"
val inPattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"
val outPattern = "dd.MM.yyyy hh:mm"
val inFormat = SimpleDateFormat(inPattern, Locale.getDefault())
val outFormat = SimpleDateFormat(outPattern, Locale.getDefault())
val inDate = inFormat.parse(dateString)
val outDate = outFormat.format(inDate)
Log.e("TEST", outDate)
If you are using java, you can use SimpeDateFormat with patterns:
String date = "2018-01-09T11:11:02.0+03:00";
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
SimpleDateFormat output = new SimpleDateFormat("dd.MM.yyyy hh:mm");
Date d = null;
try {
d = dateformat.parse(date /*your date as String*/);
} catch (ParseException e) {
e.printStackTrace();
}
String formattedDate = output.format(d);
Log.d("Date format", "output date :" + formattedDate);
The output is :
D/Date format: output date :09.01.2018 09:11
EDIT : Thanks to #OleV.V., for API > 26, or using ThreeTenABP we can use
DateTimeFormatter, we can do something like that
String date = "2018-01-09T11:11:02.0+03:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
DateTimeFormatter formatterOut = DateTimeFormatter.ofPattern("dd.MM.yyyy hh:mm");
LocalDate parsedDate = LocalDate.parse(date, formatter);
String formattedDate = formatterOut.format(parsedDate);
Log.d("Date format", "output date :" + formattedDate);
DateTimeFormatter desiredFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm");
String backendDateTimeString = "2018-01-09T11:11:02.0+03:00";
OffsetDateTime dateTime = OffsetDateTime.parse(backendDateTimeString);
String presentationDateTimeString = dateTime.format(desiredFormatter);
System.out.println(presentationDateTimeString);
This prints:
09.01.2018 11:11
Please note: I am using uppercase HH in the format pattern string. This indicates hour of day from 00 through 23. In the question you used lowercase hh, which in a format pattern string means hour with AM or PM from 01 through 12, so 00:33 would come out as 12:33 and 15:47 as 03:47. I didn’t think you intended this.
The format that your backend developer got, 2018-01-09T11:11:02.0+03:00, is ISO 8601. It’s widespread, and it’s the international standard, so it’s good that s/he got that. The funny T in the middle indicates the start of the time part to separate it from the date part. The one-arg OffsetDateTime.parse method parses ISO 8601, which is why we didn’t need any formatter for parsing. OffsetDateTime and DateTimeFormatter are classes from java.time, the modern Java date and time API.
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 (API level 26 and up) 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 (my code was tested with these imports).
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.
Wikipedia article: ISO 8601
I am trying to format a JSON which has a date key in the format:
date: "2017-05-23T06:25:50"
My current attempt is the following:
private String formatDate(String date) {
SimpleDateFormat format = new SimpleDateFormat("MM/DD/yyyy");
String formattedDate = "";
try {
formattedDate = format.format(format.parse(String.valueOf(date)));
} catch (ParseException e) {
e.printStackTrace();
}
return formattedDate;
}
But in this occasion, the result isn't shown in my app, the TextView is invisible and I couldn't log anything.
I really tried other solutions, but no success for me. I don't know if it's because the incoming value is a string.
Use this code to format your `2017-05-23T06:25:50'
String strDate = "2017-05-23T06:25:50";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date convertedDate = new Date();
try {
convertedDate = dateFormat.parse(strDate);
SimpleDateFormat sdfnewformat = new SimpleDateFormat("MMM dd yyyy");
String finalDateString = sdfnewformat.format(convertedDate);
} catch (ParseException e) {
e.printStackTrace();
}
The converted finalDateString set to your textView
This will work for you.
String oldstring= "2017-05-23T06:25:50.0";
Date datee = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(oldstring);
This code worked for me :
public static String getNewsDetailsDateTime(String dateTime) {
#SuppressLint("SimpleDateFormat") DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
Date date = null;
try {
date = format.parse(dateTime);
} catch (ParseException e) {
e.printStackTrace();
}
#SuppressLint("SimpleDateFormat") String strPublishDateTime = new SimpleDateFormat("MMM d, yyyy h:mm a").format(date);
return strPublishDateTime;
}
Out put format was : Dec 20 , 2017 2.30 pm.
Use this function :
private String convertDate(String dt) {
//String date="2017-05-23T06:25:50";
try {
SimpleDateFormat spf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); //date format in which your current string is
Date newDate = null;
newDate = spf.parse(dt);
spf = new SimpleDateFormat("MM/DD/yyyy"); //date format in which you want to convert
dt = spf.format(newDate);
System.out.println(dt);
Log.e("FRM_DT", dt);
} catch (ParseException e) {
e.printStackTrace();
}
return dt;
}
TL;DR
private static final DateTimeFormatter DATE_FORMATTER
= DateTimeFormatter.ofPattern("MM/dd/uuuu");
private static String formatDate(String date) {
return LocalDateTime.parse(date).format(DATE_FORMATTER);
}
Now formatDate("2017-05-23T06:25:50") returns the desired string of 05/23/2017.
java.time
In 2017 I see no reason why you should struggle with the long outdated and notoriously troublesome SimpleDateFormat class. java.time, the modern Java date and time API also known as JSR-310, is so much nicer to work with.
Often when converting from one date-time format to another you need two formatters, one for parsing the input format and one for formatting into the output format. Not here. This is because your string like 2017-05-23T06:25:50 is in the ISO 8601 format, the standard that the modern classes parse as their default, that is, without an explicit formatter. So we only need one formatter, for formatting.
What went wrong in your code
When I run your code, I get a ParseException: Unparseable date: "2017-05-23T06:25:50". If you didn’t notice the exception already, then you have a serious flaw in your project setup that hides vital information about errors from you. Please fix first thing.
A ParseException has a method getErrorOffset (a bit overlooked), which in this case returns 4. Offset 4 in your string is where the first hyphen is. So when parsing in the format MM/DD/yyyy, your SimpleDateFormat accepted 2017 as a month (funny, isn’t it?), then expected a slash and got a hyphen instead, and therefore threw the exception.
You’ve got another error in your format pattern string: Uppercase DD is for day-of-year (143 in this example). Lowercase dd should be used for day-of-month.
Question: Can I use java.time on Android?
Yes you can. It just requires at least Java 6.
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.
Links
Oracle tutorial: Date Time, explaining how to use java.time.
ThreeTen Backport project
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Java Specification Request (JSR) 310, where the modern date and time API was first described.
Try this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
try {
c.setTime(sdf.parse(dt));
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
String output = sdf1.format(c.getTime());
I have an app that displays dates and times in a localized format for different areas, that is - it shows a user dates and times based on his preference. But my issue is that it always displays numbers, ie yyyy.mm.dd, or mm/dd/yyy, or dd,mm,yyyy. What I would like to have is this: show date so that the day is a number, year is a number, but the month is displayed as a string, ie. Jan / Xin / Gen / Jān / Yan... or 01 Jan 2018 / Jan 01 2018 / 2018 Jan 01, and so on, but still keep the current local formatting. I know that I could do that if I hardcode it like MMM, but I want it to change, depending on the localized format.
So basically this is my question: how can I display localized time, from a value I get from the server (yyyy-MM-dd HH: mm: ss), with month displayed as a three letter word, no matter what locale it uses?
I know this question sounds familiar, but so far I have tried a lot of answers, both on stack overflow, and other sources, but without any success. Some of the things I have tried include: 1 / 2 / 3 / 4 / 5 / 6 ... but I couldn't make it work in my example.
My Adapter:
public void onBindViewHolder(RestaurantsAdapter.RestaurantsViewHolder holder, int position) {
// getting restaurant data for the row
Restaurant restaurant = restaurant Items.get(position);
holder.userName.setText(restaurant .getUserName());
holder.date.setText(convertDate(restaurant .getDateTime())); //string dobiti u formatu, pretvoriti ga u localized i podijeliti na dva dijela
holder.time.setText(convertTime(restaurant .getDateTime()));
TextDrawable.IBuilder builder = TextDrawable.builder()
.beginConfig()
.withBorder(0)
.toUpperCase()
.endConfig()
.roundRect(10);
ColorGenerator generator = ColorGenerator.MATERIAL;
int color = generator.getColor(restaurant.getUserId());
TextDrawable textDrawable = builder.build(restaurant Items.get(position).getUserName().substring(0, 1), color);
holder.thumbNail.setImageDrawable(textDrawable);
Picasso.with(context)
.load(AppConfig.URL_PROFILE_PHOTO + restaurant.getThumbnailUrl())
.placeholder(textDrawable)
.error(textDrawable)
.transform(new RoundedTransform(12, 0))
.fit()
.centerCrop()
.into(holder.thumbNail);
}
private String convertDate(String time) {
final DateFormat shortDateFormat = android.text.format.DateFormat.getDateFormat(context.getApplicationContext());
SimpleDateFormat dateFormatReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
SimpleDateFormat dateFormatConverted = new SimpleDateFormat(((SimpleDateFormat) shortDateFormat).toPattern(), Locale.getDefault());
java.util.Date date = null;
try {
date = dateFormatReceived.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
return dateFormatConverted.format(date);
}
private String convertTime(String time) {
final DateFormat shortTimeFormat = android.text.format.DateFormat.getTimeFormat(context.getApplicationContext());
SimpleDateFormat timeFormatReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
SimpleDateFormat timeFormatConverted = new SimpleDateFormat(((SimpleDateFormat) shortTimeFormat).toPattern(), Locale.getDefault());
java.util.Date date = null;
try {
date = timeFormatReceived.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
return timeFormatConverted.format(date);
}
UPDATE:
I tried adding this to my solution:
private String convertDate(String time) {
final DateFormat shortDateFormat = android.text.format.DateFormat.getDateFormat(context.getApplicationContext());
Calendar Now = Calendar.getInstance();
Now.getDisplayName(Calendar.HOUR, Calendar.SHORT, Locale.getDefault());
SimpleDateFormat dateFormatReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
SimpleDateFormat dateFormatConverted = new SimpleDateFormat(((SimpleDateFormat) shortDateFormat).toPattern(), Locale.getDefault());
dateFormatConverted.getDisplayName(Calendar.HOUR, Calendar.SHORT, Locale.getDefault());
java.util.Date date = null;
try {
date = dateFormatReceived.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
return dateFormatConverted.format(date);
}
I think the following method will give you the date-time formatter you want.
public static DateTimeFormatter getLocalizedDateFormatter(Locale requestedLocale) {
String formatPatternString = DateTimeFormatterBuilder.getLocalizedDateTimePattern(
FormatStyle.SHORT, null,
Chronology.ofLocale(requestedLocale), requestedLocale);
// if not already showing month name, modify so it shows abbreviated month name
if (! formatPatternString.contains("MMM")) {
formatPatternString = formatPatternString.replaceAll("M+", "MMM");
}
return DateTimeFormatter.ofPattern(formatPatternString, requestedLocale);
}
Test:
Locale[] locales = { Locale.US, Locale.FRANCE, Locale.GERMANY,
Locale.forLanguageTag("da-DK"), Locale.forLanguageTag("sr-BA") };
LocalDate today = LocalDate.now(ZoneId.of("Europe/Sarajevo"));
for (Locale currentLocale : locales) {
DateTimeFormatter ldf = getLocalizedDateFormatter(currentLocale);
System.out.format(currentLocale, "%-33S%s%n",
currentLocale.getDisplayName(), today.format(ldf));
}
Output:
ENGLISH (UNITED STATES) Dec/24/17
FRENCH (FRANCE) 24/déc./17
GERMAN (GERMANY) 24.Dez.17
DANSK (DANMARK) 24-dec.-17
SERBIAN (BOSNIA AND HERZEGOVINA) 17-дец-24
JSR-310 also known as java.time
You tried to use the long outdated and notoriously troublesome classes DateFormat and SimpleDateFormat. Instead I recommend you make it a habit to use JSR-310, the modern Java date and time API. So I do that in the method above.
I don’t think it was part of the question, but for the sake of completeness, parse the date-time string as follows. The formatter you get from my getLocalizedDateFormatter can be used for formatting a LocalDateTime and many other date-time types in addition to LocalDate.
LocalDateTime ldt = LocalDateTime.parse("2017-12-24 22:51:34",
DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"));
String formattedDate = ldt.format(getLocalizedDateFormatter(Locale.UK));
Question: Can I use JSR-310 on Android?
Yes you can. It just requires at least Java 6.
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.
In the latter two cases, make sure to add the appropriate edition of the backport library to your project, use the links below, and to import the classes I use from org.threeten.bp and org.threeten.bp.format.
Links
Oracle tutorial: Date Time, explaining how to use java.time.
ThreeTen Backport project
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Java Specification Request (JSR) 310, where the modern date and time API was first described.
Please try to use
getDisplayName(...) method
In order to get more information you had better go through this documentation
Editted
More sufficiently you can try this way:
int monthOfYear = Calendar.JULY; // 6
String monthName = new
DateFormatSymbols(Locale.getDefault()).getShortMonths()[monthOfYear];
I have two Date objects with the below format.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
String matchDateTime = sdf.parse("2014-01-16T10:25:00");
Date matchDateTime = null;
try {
matchDateTime = sdf.parse(newMatchDateTimeString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// get the current date
Date currenthDateTime = null;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date dt = new Date();
String currentDateTimeString = dateFormat.format(dt);
Log.v("CCCCCurrent DDDate String is:", "" + currentDateTimeString);
try {
currenthDateTime = sdf.parse(currentDateTimeString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Now I want to compare the above two dates along with time.
How should I compare in Java.
Thanks
Since Date implements Comparable<Date>, it is as easy as:
date1.compareTo(date2);
As the Comparable contract stipulates, it will return a negative integer/zero/positive integer if date1 is considered less than/the same as/greater than date2 respectively (ie, before/same/after in this case).
Note that Date has also .after() and .before() methods which will return booleans instead.
An Alternative is....
Convert both dates into milliseconds as below
Date d = new Date();
long l = d.getTime();
Now compare both long values
Use compareTo()
Return Values
0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument.
Like
if(date1.compareTo(date2)>0)
An alternative is Joda-Time.
Use DateTime
DateTime date = new DateTime(new Date());
date.isBeforeNow();
or
date.isAfterNow();
// Get calendar set to the current date and time
Calendar cal = Calendar.getInstance();
// Set time of calendar to 18:00
cal.set(Calendar.HOUR_OF_DAY, 18);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
// Check if current time is after 18:00 today
boolean afterSix = Calendar.getInstance().after(cal);
if (afterSix) {
System.out.println("Go home, it's after 6 PM!");
}
else {
System.out.println("Hello!");
}
The other answers are generally correct and all outdated. Do use java.time, the modern Java date and time API, for your date and time work. With java.time your job has also become a lot easier compared to the situation when this question was asked in February 2014.
String dateTimeString = "2014-01-16T10:25:00";
LocalDateTime dateTime = LocalDateTime.parse(dateTimeString);
LocalDateTime now = LocalDateTime.now(ZoneId.systemDefault());
if (dateTime.isBefore(now)) {
System.out.println(dateTimeString + " is in the past");
} else if (dateTime.isAfter(now)) {
System.out.println(dateTimeString + " is in the future");
} else {
System.out.println(dateTimeString + " is now");
}
When running in 2020 output from this snippet is:
2014-01-16T10:25:00 is in the past
Since your string doesn’t inform of us any time zone or UTC offset, we need to know what was understood. The code above uses the device’ time zone setting. For a known time zone use like for example ZoneId.of("Asia/Ulaanbaatar"). For UTC specify ZoneOffset.UTC.
I am exploiting the fact that your string is in ISO 8601 format. The classes of java.time parse the most common ISO 8601 variants without us having to give any formatter.
Question: For Android development 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
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.
Wikipedia article: ISO 8601