Parse String to Date with Different Format in Java
Take a look at SimpleDateFormat
. The code goes something like this:
SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
String reformattedStr = myFormat.format(fromUser.parse(inputString));
} catch (ParseException e) {
e.printStackTrace();
}
Convert String Date to String date different format
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat format2 = new SimpleDateFormat("dd-MM-yyyy");
Date date = format1.parse("2013-02-21");
System.out.println(format2.format(date));
Formatting a String date into a different format in Java
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
String to date format and vice versa
java.time
I strongly recommend that you use java.time, the modern Java date and time API, for your date work.
It generally takes two formatters for converting a string date in one format to a string in another format: one for describing the format you got, and one for the required format. In this case the former is built in. For your required result define a formatter statically:
private static final DateTimeFormatter DATE_FORMATTER
= DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
.withLocale(Locale.forLanguageTag("es-PA"));
The do:
String dateFormat = "20211109";
LocalDate start = LocalDate.parse(dateFormat, DateTimeFormatter.BASIC_ISO_DATE);
String string = start.format(DATE_FORMATTER);
System.out.println(string);
Output:
11/09/2021
For formatting I took the built-in medium date format for Panama since this is one of the locales where the format fits what you asked for. You should of course use your users’ locale, not the one of Panama, for an output format that they will recognize as their own. In this way we are saving ourselves the trouble of composing a format pattern string, and at the same time the code lends itself excellently to internationalization.
You shouldn’t want to convert from one string format to another
If you are asking how to convert a date from one string format to another, you are really asking the wrong question. In all but the smallest throw-away programs, we should not handle dates as strings, but always store them in LocalDate
objects. When we take string input, we parse. Only when we need to give string output, we format back.
Using a format pattern
If for one reason or another your users are not happy with Java’s localized format, and you need more control over the output format, you may use a format pattern as you tried in your question:
private static final DateTimeFormatter DATE_FORMATTER
= DateTimeFormatter.ofPattern("MM/dd/yyyy", Locale.ROOT);
Links
- Oracle tutorial: Date Time explaining how to use java.time.
- Wikipedia article: ISO 8601
- Related question: error output converting date format from YYYYMMDD to dd-mm-yyyy
- Related question: String to date format java
How to convert String to Date with a specific format in java
The class Date
will always contain both date a nd time information, since it represents an instant in time.
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ParsingDate {
public static void main(String[] args) {
DateFormat fmt = new SimpleDateFormat("dd-MM-yyyy");
Date d;
try {
d = fmt.parse("04-12-2019");
System.out.println(d); // Wed Dec 04 00:00:00 CET 2019
} catch (ParseException e) {
e.printStackTrace();
}
}
}
As you can see, hours, minutes, seconds and millis get all set to 0.
If you later want to output the date in string format, you need to use the DateFormat#format(Date)
method:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ParsingDate {
public static void main(String[] args) {
DateFormat fmt = new SimpleDateFormat("dd-MM-yyyy");
Date d = new Date();
System.out.println(d); // Wed Dec 04 11:24:35 CET 2019
System.out.println(fmt.format(d)); // 04-12-2019
}
}
If you'd rather store only date information, you could use the java.time
package and make use of LocalDate
.LocalDate
stores only date information, since it does not represent an instant, rather a triple of year, month and date.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class ParsingLocalDate {
public static void main(String[] args) {
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate d = LocalDate.parse("04-12-2019", fmt);
System.out.println(d); // 2019-12-04
}
}
Parse string to date using different formats/patterns
Update to use parseDateStrictly
. When I did this I got the following output:
2013-09-30:Mon Sep 30 00:00:00 EDT 2013
30-09-2013:Mon Sep 30 00:00:00 EDT 2013
How to Parse different Date formats from String in Java (FAQ)
Avoid legacy date-time classes
The old Date
, Calendar
, and SimpleDateFormat
classes are an awful sour mess of poor design. Never use them. Now supplanted by the java.time classes.
Parsing
First test if input string equals "null".
Next, parse the first format with simply LocalDate.parse( "1987-03-23" )
and trap for exception. That standard ISO 8601 format is handled by default, so no need to specify a formatting pattern.
Lastly, define a formatting pattern DateTimeFormatter.ofPatten( "dd-MM-uuuu" )
and parse with that, calling LocalDate.parse( input , formatter )
. Trap for exception.
If all those fail, you have unexpected inputs.
Generating strings
Once you have a LocalDate
object in hand, generate a string using LocalDate.format
where you pass a DateTimeFormatter
. You can define a formatting pattern as seen above. Or, you can call DateTimeFormatter.ofLocalizedDate
to let java.time automatically localize for you.
Search Stack Overflow
This has been covered many many times already. Search Stack Overflow for these class names, to see more detail and more code.
I suggest using a search engine with site:stackoverflow.com
criteria as the built-in search feature in Stack Overflow is weak and tends to ignore Answers, biasing towards only Questions.
For example, do this:
https://duckduckgo.com/?q=site%3Astackoverflow.com+java+DateTimeFormatter&t=h_&ia=web
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
- Java SE 8, Java SE 9, Java SE 10, and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and Java SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.time classes.
- For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Related Topics
Struts2 Input Result: How Does It Work? How Are Conversion/Validation Errors Handled
Classnotfoundexception Com.Mysql.Jdbc.Driver
Using Env Variable in Spring Boot's Application.Properties
Array of JSON Object to Java Pojo
Where Is Array's Length Property Defined
Java: Parse Int Value from a Char
Java Error: Implicit Super Constructor Is Undefined for Default Constructor
How to Get a List of Dates Between Two Dates in Java
Why Does Inetaddress.Isreachable Return False, When I Can Ping the Ip Address
How to Map an Entity Field Whose Name Is a Reserved Word in JPA
"Code Too Large" Compilation Error in Java
No Appenders Could Be Found for Logger(Log4J)
How to Make the Division of 2 Ints Produce a Float Instead of Another Int