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());
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.
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 am little bit confused in dates. I am currently working on the weather app and everything works fine .. I just wanna handle this type of format into my own desirable format.
2017-09-10T18:35:00+05:00
I just wanna convert this date into Epoch Time and then I settle the date in my desire format ::
for J-SON
or i wanna convert this date into less figure i.e Sun , 9 september 9:23 Am etc.
http://dataservice.accuweather.com/currentconditions/v1/257072?apikey=JTgPZ8wN9VUy07GaOODeZfZ3sAM12irH&language=en-us&details=true
ThreeTenABP
The other answers are correct, but outdated before they were written. These days I recommend you use the modern Java date and time API known as JSR-310 or java.time. Your date-time string format is ISO 8601, which the modern classes “understand” as their default.
Can you use the modern API on Android yet? Most certainly! The JSR-310 classes have been backported to Android in the ThreeTenABP project. All the details are in this question: How to use ThreeTenABP in Android Project.
long epochTime = OffsetDateTime.parse("2017-09-10T18:35:00+05:00")
.toInstant()
.getEpochSecond();
The result is 1505050500.
Edit: Arvind Kumar Avinash correctly points out in a comment: You do not need to convert an OffsetDateTime to an Instant to get the epoch seconds. You can simply use OffsetDateTime#toEpochSecond.
Example of how to convert this into a human-readable date and time:
String formattedDateTime = Instant.ofEpochSecond(epochTime)
.atZone(ZoneId.of("Africa/Lusaka"))
.format(DateTimeFormatter.ofPattern("EEE, d MMMM h:mm a", Locale.ENGLISH));
This produces Sun, 10 September 3:35 PM. Please provide the correct region and city for the time zone ID you want. If you want to rely on the device’s time zone setting, use ZoneId.systemDefault(). See the documentation of DateTimeFormatter.ofPattern() for the letters you may use in the format pattern string, or use DateTimeFormatter.ofLocalizedDateTime() for one of your locale’s default formats.
Use a SimpleDateFormat instance to parse the string into a Date object:
DateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
Date date = parser.parse("2017-09-10T18:35:00+05:00");
And then use another SimpleDateFormat to display it:
DateFormat format = new SimpleDateFormat("EEE, dd MMMMM h:mm a");
String formatted = format.format(date); // Sun, 10 September 1:35 PM
You can use SimpleDate formatter to parse you date as string into epoch
String input = "2017-09-10T18:35:00+05:00";
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
try {
Date date = sf.parse(input);
long dateInEpochFormatInMilliSeconds = date.getTime();
//if you want this in seconds then
long dateInEpochFormatInSeconds = date.getTime()/1000L;
//if you want to show only date month and year then
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String date = sdf.format(dateInEpochFormatInMilliSeconds);
//This date String will contain the date in dd-MM-yyyy format
} catch (ParseException| ArithmeticException e) {
e.printStackTrace();
}
String time_at_which_weather_capture = "Time : ";
DateFormat dateFormat = new SimpleDateFormat("EEE,d M yyyy h:MM a");
long timeInMillieSec = 0 ;
try {
Date date = dateFormat.parse(readyToUpdate.getTime());
timeInMillieSec = date.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
time.setText(time_at_which_weather_capture + String.valueOf(time_fetcher(timeInMillieSec)));
public String time_fetcher (long time_coming_to_its_original_form) {
Date date = new Date (time_coming_to_its_original_form);
SimpleDateFormat sdf = new SimpleDateFormat("EEE, d M yyyy h:MM a");
return sdf.format(date);
}
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.
I am trying to use the Android SimpleDateFormat like this:
String _Date = "2010-09-29 08:45:22"
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = fmt.parse(_Date);
return fmt.format(date);
}
catch(ParseException pe) {
return "Date";
}
The result is good and I have: 2010-09-29
But if I change the SimpleDateFormat to
SimpleDateFormat("dd-MM-yyyy");
the problem is that I will got 03-03-0035 !!!!
Why and how to get the format like dd-MM-yyyy?
I assume you would like to reverse the date format?
SimpleDateFormat can be used for parsing and formatting.
You just need two formats, one that parses the string and the other that returns the desired print out:
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
Date date = fmt.parse(dateString);
SimpleDateFormat fmtOut = new SimpleDateFormat("dd-MM-yyyy");
return fmtOut.format(date);
Since Java 8:
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneOffset.UTC);
TemporalAccessor date = fmt.parse(dateString);
Instant time = Instant.from(date);
DateTimeFormatter fmtOut = DateTimeFormatter.ofPattern("dd-MM-yyyy").withZone(ZoneOffset.UTC);
return fmtOut.format(time);
Below is all date formats available, read more doc here.
Symbol Meaning Kind Example
D day in year Number 189
E day of week Text E/EE/EEE:Tue, EEEE:Tuesday, EEEEE:T
F day of week in month Number 2 (2nd Wed in July)
G era designator Text AD
H hour in day (0-23) Number 0
K hour in am/pm (0-11) Number 0
L stand-alone month Text L:1 LL:01 LLL:Jan LLLL:January LLLLL:J
M month in year Text M:1 MM:01 MMM:Jan MMMM:January MMMMM:J
S fractional seconds Number 978
W week in month Number 2
Z time zone (RFC 822) Time Zone Z/ZZ/ZZZ:-0800 ZZZZ:GMT-08:00 ZZZZZ:-08:00
a am/pm marker Text PM
c stand-alone day of week Text c/cc/ccc:Tue, cccc:Tuesday, ccccc:T
d day in month Number 10
h hour in am/pm (1-12) Number 12
k hour in day (1-24) Number 24
m minute in hour Number 30
s second in minute Number 55
w week in year Number 27
G era designator Text AD
y year Number yy:10 y/yyy/yyyy:2010
z time zone Time Zone z/zz/zzz:PST zzzz:Pacific Standard
I think this Link might helps you
OR
Date date = Calendar.getInstance().getTime();
//
// Display a date in day, month, year format
//
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String today = formatter.format(date);
System.out.println("Today : " + today);
String _Date = "2010-09-29 08:45:22"
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat fmt2 = new SimpleDateFormat("dd-MM-yyyy");
try {
Date date = fmt.parse(_Date);
return fmt2.format(date);
}
catch(ParseException pe) {
return "Date";
}
try this.
Using the date-time API of java.util and their formatting API, SimpleDateFormat I have come across surprises several times but this is the biggest one! 😮😮😮
Given below is the illustration of what you have described in your question:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
class Main {
public static void main(String[] args) {
System.out.println(formatDateWithPattern1("2010-09-29 08:45:22"));
System.out.println(formatDateWithPattern2("2010-09-29 08:45:22"));
}
static String formatDateWithPattern1(String strDate) {
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = fmt.parse(strDate);
return fmt.format(date);
} catch (ParseException pe) {
return "Date";
}
}
static String formatDateWithPattern2(String strDate) {
SimpleDateFormat fmt = new SimpleDateFormat("dd-MM-yyyy");
try {
Date date = fmt.parse(strDate);
return fmt.format(date);
} catch (ParseException pe) {
return "Date";
}
}
}
Output:
2010-09-29
03-03-0035
Surprisingly, SimpleDateFormat silently performed the parsing and formatting without raising an alarm. Anyone reading this will not have a second thought to stop using them completely and switch to the modern date-time API.
For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7.
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.
Using the modern date-time API:
Since the pattern used in both the functions are wrong as per the input string, the parser should raise the alarm and the parsing/formatting types of the modern date-time API do it responsibly.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
class Main {
public static void main(String[] args) {
System.out.println(formatDateWithPattern1("2010-09-29 08:45:22"));
System.out.println(formatDateWithPattern2("2010-09-29 08:45:22"));
}
static String formatDateWithPattern1(String strDate) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd");
try {
LocalDateTime date = LocalDateTime.parse(strDate, dtf);
return dtf.format(date);
} catch (DateTimeParseException dtpe) {
return "Date";
}
}
static String formatDateWithPattern2(String strDate) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-uuuu");
try {
LocalDateTime date = LocalDateTime.parse(strDate, dtf);
return dtf.format(date);
} catch (DateTimeParseException dtpe) {
return "Date";
}
}
}
Output:
Date
Date
Moral of the story
The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. Stop using them completely and switch to the modern date-time API. Learn about the modern date-time API at Trail: Date Time.
Stick to the format in your input date-time string while parsing it. If you want the output in a different format, use a differnt instance of the parser/formatter class.
Demo:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
class Main {
public static void main(String[] args) {
String strDateTime = "2010-09-29 08:45:22";
DateTimeFormatter dtfForParsing = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
LocalDateTime ldt = LocalDateTime.parse(strDateTime, dtfForParsing);
System.out.println(ldt);// The default format as returned by LocalDateTime#toString
// Some custom formats for output
System.out.println("########In custom formats########");
DateTimeFormatter dtfForFormatting1 = DateTimeFormatter.ofPattern("dd-MM-uuuu HH:mm:ss");
DateTimeFormatter dtfForFormatting2 = DateTimeFormatter.ofPattern("dd-MM-uuuu");
DateTimeFormatter dtfForFormatting3 = DateTimeFormatter.ofPattern("'Day: 'EEEE, 'Date: 'MMMM dd uuuu");
System.out.println(dtfForFormatting1.format(ldt));
System.out.println(dtfForFormatting2.format(ldt));
System.out.println(dtfForFormatting3.format(ldt));
System.out.println("################################");
}
}
Output:
2010-09-29T08:45:22
########In custom formats########
29-09-2010 08:45:22
29-09-2010
Day: Wednesday, Date: September 29 2010
################################
This worked for me...
#SuppressLint("SimpleDateFormat")
private void setTheDate() {
long msTime = System.currentTimeMillis();
Date curDateTime = new Date(msTime);
SimpleDateFormat formatter = new SimpleDateFormat("MM'/'dd'/'y hh:mm");
curDate = formatter.format(curDateTime);
mDateText.setText("" + curDate);
}
java.time and desugaring
I recommend that you use java.time, the modern Java date and time API, for your date work. First define a formatter for your string:
private static DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
Then do:
String dateString = "2010-09-29 08:45:22";
LocalDateTime dateTime = LocalDateTime.parse(dateString, formatter);
String newString = dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE);
System.out.println(newString);
Output is:
2010-09-29
I find it a good practice to parse the entire string even though we currently have no use for the time of day. That may come some other day. java.time furnishes a predefined formatter for your first output format, DateTimeFormatter.ISO_LOCAL_DATE. If you want the opposite order of day, month and year, we will need to write our own formatter for that:
private static DateTimeFormatter dateFormatter
= DateTimeFormatter.ofPattern("dd-MM-uuuu");
Then we can obtain that too:
String dmyReversed = dateTime.format(dateFormatter);
System.out.println(dmyReversed);
29-09-2010
What went wrong in your code?
the problem is that I will got 03-03-0035 !!!!
This is how confusing a SimpleDateFormat with standard settings is: With format pattern dd-MM-yyyy it parses 2010-09-29 as the 2010th day of month 9 of year 29. Year 29 AD that is. And it doesn’t disturb it that there aren’t 2010 days in September. It just keeps counting days through the following months and years and ends up five and a half years later, on 3 March year 35.
Which is just a little bit of the reason why I say: don’t use that class.
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 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.
uuuu versus yyyy in DateTimeFormatter formatting pattern codes in Java?
Wikipedia article: ISO 8601
Here is an easy example of SimpleDateFormat tried in Android Studio 3 and Java 9:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
String strDate = sdf.format(strDate);
Note:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); shows
some deprecation warning in Android Studio 3 Lint. So, add a second
parameter Locale.US to specify the Localization in date formatting.
It took a lot of efforts. I did a lot of hit and trial and finally I got the solution. I had used ""MMM"" for showing month as: JAN
If you looking for date, month and year separately
or how to use letters from answer of heloisasim
SimpleDateFormat day = new SimpleDateFormat("d");
SimpleDateFormat month = new SimpleDateFormat("M");
SimpleDateFormat year = new SimpleDateFormat("y");
Date d = new Date();
String dayS = day.format(d);
String monthS = month.format(d);
String yearS = year.format(d);
public String formatDate(String dateString) {
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = fmt.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat fmtOut = new SimpleDateFormat("dd-MM-yyyy");
return fmtOut.format(date);
}