Java string to date conversion
That's the hard way, and those java.util.Date
setter methods have been deprecated since Java 1.1 (1997). Moreover, the whole java.util.Date
class was de-facto deprecated (discommended) since introduction of java.time
API in Java 8 (2014).
Simply format the date using DateTimeFormatter
with a pattern matching the input string (the tutorial is available here).
In your specific case of "January 2, 2010" as the input string:
- "January" is the full text month, so use the
MMMM
pattern for it - "2" is the short day-of-month, so use the
d
pattern for it. - "2010" is the 4-digit year, so use the
yyyy
pattern for it.
String string = "January 2, 2010";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH);
LocalDate date = LocalDate.parse(string, formatter);
System.out.println(date); // 2010-01-02
Note: if your format pattern happens to contain the time part as well, then use LocalDateTime#parse(text, formatter)
instead of LocalDate#parse(text, formatter)
. And, if your format pattern happens to contain the time zone as well, then use ZonedDateTime#parse(text, formatter)
instead.
Here's an extract of relevance from the javadoc, listing all available format patterns:
Symbol | Meaning | Presentation | Examples |
---|---|---|---|
G | era | text | AD; Anno Domini; A |
u | year | year | 2004; 04 |
y | year-of-era | year | 2004; 04 |
D | day-of-year | number | 189 |
M /L | month-of-year | number/text | 7; 07; Jul; July; J |
d | day-of-month | number | 10 |
Q /q | quarter-of-year | number/text | 3; 03; Q3; 3rd quarter |
Y | week-based-year | year | 1996; 96 |
w | week-of-week-based-year | number | 27 |
W | week-of-month | number | 4 |
E | day-of-week | text | Tue; Tuesday; T |
e /c | localized day-of-week | number/text | 2; 02; Tue; Tuesday; T |
F | week-of-month | number | 3 |
a | am-pm-of-day | text | PM |
h | clock-hour-of-am-pm (1-12) | number | 12 |
K | hour-of-am-pm (0-11) | number | 0 |
k | clock-hour-of-am-pm (1-24) | number | 0 |
H | hour-of-day (0-23) | number | 0 |
m | minute-of-hour | number | 30 |
s | second-of-minute | number | 55 |
S | fraction-of-second | fraction | 978 |
A | milli-of-day | number | 1234 |
n | nano-of-second | number | 987654321 |
N | nano-of-day | number | 1234000000 |
V | time-zone ID | zone-id | America/Los_Angeles; Z; -08:30 |
z | time-zone name | zone-name | Pacific Standard Time; PST |
O | localized zone-offset | offset-O | GMT+8; GMT+08:00; UTC-08:00; |
X | zone-offset 'Z' for zero | offset-X | Z; -08; -0830; -08:30; -083015; -08:30:15; |
x | zone-offset | offset-x | +0000; -08; -0830; -08:30; -083015; -08:30:15; |
Z | zone-offset | offset-Z | +0000; -0800; -08:00; |
How can i convert String to Date when it has TRT in it
Where your code failed:
SimpleDateFormat sdf1=new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
String dateStr = "06.08.2020";
sdf1.parse(dateStr);
As you can see, the pattern of the SimpleDateFormat
and that of the date
string do not match and therefore, this code will throw ParseException
.
How to make it work?
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
String dateStr = "06.08.2020";
Date date = sdf.parse(dateStr);
You must have already got why it worked. It worked because the pattern of the SimpleDateFormat
matches with that of the dateStr
string.
Can I format the Date
object (i.e. date
) into the original string?
Yes, just use the same format which you used to parse the original string as shown below:
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
String dateStr = "06.08.2020";
Date date = sdf.parse(dateStr);
// Display in the default format
System.out.println(date);
// Format into the string
dateStr = sdf.format(date);
System.out.println(dateStr);
A piece of advice:
I recommend you switch from the outdated and error-prone java.util
date-time API and SimpleDateFormat
to the modern java.time
date-time API and the corresponding formatting API (package, java.time.format
). Learn more about the modern date-time API from Trail: Date Time.
Using the modern date-time API:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
String dateStr = "06.08.2020";
LocalDate date = LocalDate.parse(dateStr, formatter);
// Display in the default format
System.out.println(date);
// Format into the string
dateStr = formatter.format(date);
System.out.println(dateStr);
I don't see any difference using the legacy API and the modern API:
That's true for this simple example but when you will need to do complex operations using date and time, you will find the modern date-time API smart and clean while the legacy API complex and error-prone.
Demo:
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// Given date-time string
String strDate = "Thu Aug 06 00:00:00 TRT 2020";
// Replace TRT with standard time-zone string
strDate = strDate.replace("TRT", "Europe/Istanbul");
// Define formatter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzzz yyyy");
// Parse the date-time string into ZonedDateTime
ZonedDateTime zdt = ZonedDateTime.parse(strDate, formatter);
System.out.println(zdt);
// If you wish, convert ZonedDateTime into LocalDateTime
LocalDateTime ldt = zdt.toLocalDateTime();
System.out.println(ldt);
}
}
Output:
2020-08-06T00:00+03:00[Europe/Istanbul]
2020-08-06T00:00
Convert java.util.Date to String
Convert a Date to a String using DateFormat#format
method:
String pattern = "MM/dd/yyyy HH:mm:ss";
// Create an instance of SimpleDateFormat used for formatting
// the string representation of date according to the chosen pattern
DateFormat df = new SimpleDateFormat(pattern);
// Get the today date using Calendar object.
Date today = Calendar.getInstance().getTime();
// Using DateFormat format method we can create a string
// representation of a date with the defined format.
String todayAsString = df.format(today);
// Print the result!
System.out.println("Today is: " + todayAsString);
From http://www.kodejava.org/examples/86.html
how to convert java string to Date object
You basically effectively converted your date in a string format to a date object. If you print it out at that point, you will get the standard date formatting output. In order to format it after that, you then need to convert it back to a date object with a specified format (already specified previously)
String startDateString = "06/27/2007";
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date startDate;
try {
startDate = df.parse(startDateString);
String newDateString = df.format(startDate);
System.out.println(newDateString);
} catch (ParseException e) {
e.printStackTrace();
}
Change a Java date-time string to date
You need to use the SimpleDateFormat:
String sDate = "2018-01-17 00:00:00";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = df.parse(sDate);
SimpleDateFormat df1 = new SimpleDateFormat("dd-MM-yyyy");
System.out.println(df1.format(date));
Go through the SimpleDateFormat class to get into details for this
Convert String to Date with Milliseconds
The Date class stores the time as milliseconds, and if you look into your date object you will see that it actually has a time of 1598515567413 milliseconds.
You are fooled by the System.out.println() which uses Date's toString() method. This method is using the "EEE MMM dd HH:mm:ss zzz yyyy" format to display the date and simply omits all milliseconds.
If you use your formatter, which has milliseconds in its format string, you will see that the milliseconds are correct:
System.out.println(formatter.format(dateFormatter));
outputs 2020-08-27T10:06:07.413
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
Java String to DateTime
You can create Joda DateTime object from the Java Date object, since Java does not have a DateTime
class.
DateTime dt = new DateTime(start.getTime());
Though the Date
class of Java holds the time information as well(that's what you need in the first place), I suggest you to use a Calendar
instead of the Date
class of Java.
Calendar myCal = new GregorianCalendar();
myCal.setTime(date);
Have a look at the Calendar docs for more info on how you can use it more effectively.
Things have changed and now even Java (Java 8 to be precise), has a LocalDateTime and ZonedDateTime class. For conversions, you can have a look at this SO answer(posting an excerpt from there).
Given: Date date = [some date]
(1) LocalDateTime << Instant<< Date
Instant instant = Instant.ofEpochMilli(date.getTime());
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
(2) Date << Instant << LocalDateTime
Instant instant = ldt.toInstant(ZoneOffset.UTC);
Date date = Date.from(instant);
how to format String to Date with format dd-mm-yyyy in java
tl;dr
LocalDate
.parse( "2022-05-12" )
.format(
DateTimeFormatter.ofPattern( "dd-MM-uuuu" )
)
12-05-2022
java.time
Use modern java.time classes. Never use the terrible Date
, Calendar
, SimpleDateFormat
classes.
ISO 8601
Your input conforms to ISO 8601 standard format used by default in the java.time classes for parsing/generating text. So no need to specify a formatting pattern.
LocalDate
Parse your date-only input as a date-only object, a LocalDate
.
String input = "2022-05-12" ;
LocalDate ld = LocalDate.parse( input ) ;
To generate text in your desired format, specify a formatting pattern.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ;
String output = ld.format( f ) ;
Rather than hardcode a particular pattern, I suggest learning to automatically localize using DateTimeFormatter.ofLocalizedDate
.
All this has been covered many many times already on Stack Overflow. Always search thoroughly before posting. Search to learn more.
Related Topics
Must Override a Superclass Method' Errors After Importing a Project into Eclipse
Relation Between Memory Host and Memory Arguments Xms and Xmx from Java
How to Upload Files to a Server Using Jsp/Servlet
Java Inner Class and Static Nested Class
What Is a Numberformatexception and How to Fix It
How to Get the Path of a Running Jar File
How to Use the Tostring Method in Java
Generating Unique Random Numbers in Java
Javafx 8 Compatibility Issues - Fxml Static Fields
Collision Detection With Complex Shapes
How to Get a Resource Content from a Static Context
How to Deal With Linkageerrors in Java
Servlet Returns "Http Status 404 the Requested Resource (/Servlet) Is Not Available"
How to Convert My Java Program to an .Exe File
Why Is Java Vector (And Stack) Class Considered Obsolete or Deprecated
Why Don't Java'S +=, -=, *=, /= Compound Assignment Operators Require Casting