How to convert a String to a Date using SimpleDateFormat?
Try this:
new SimpleDateFormat("MM/dd/yyyy")
MM
is "month" (notmm
)dd
is "day" (notDD
)
It's all in the javadoc for SimpleDateFormat
FYI, the reason your format is still a valid date format is that:
mm
is "minutes"DD
is "day in year"
Also, you don't need the cast to Date
... it already is a Date
(or it explodes):
public static void main(String[] args) throws ParseException {
System.out.println(new SimpleDateFormat("MM/dd/yyyy").parse("08/16/2011"));
}
Output:
Tue Aug 16 00:00:00 EST 2011
Voila!
how to convert String to date using simpledateformat
Try as follows...
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date;
@SuppressLint("SimpleDateFormat")
public static Date getDate(String string){
date = new Date();
try {
date = format.parse(string);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
Convert String to Util Date using simpleDateFormat not working
You'll need 2 SimpleDateFormat objects for that. One to parse your current date string and the other to format that parsed date to your desired format.
// This is to parse your current date string
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String startDate = "2013-09-25";
Date frmDate = sdf.parse(startDate); // Handle the ParseException here
// This is to format the your current date to the desired format
DateFormat sdff = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String frmDateStr = sdff.format(frmDate);
Edit:-
Date
doesn't have a format as such. You can only get a String representation of it using the SDF. Here an excerpt from the docs
A thin wrapper around a millisecond value that allows JDBC to identify
this as an SQL DATE value. A milliseconds value represents the number
of milliseconds that have passed since January 1, 1970 00:00:00.000
GMT.
And regarding your problem to insert it in the DB, java Date
can be as such persisted in the DB date format. You don't need to do any formatting. Only while fetching the date back from DB, you can use the to_char()
method to format it.
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
Convert string to date then format the date
Use SimpleDateFormat#format(Date):
String start_dt = "2011-01-01";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-DD");
Date date = (Date)formatter.parse(start_dt);
SimpleDateFormat newFormat = new SimpleDateFormat("MM-dd-yyyy");
String finalString = newFormat.format(date);
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));
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; |
Related Topics
Is There a Good Natural Language Processing Library
Read Properties File Outside Jar File
Getting the Class Name from a Static Method in Java
Execute Method on Startup in Spring
Why Invoke Thread.Currentthread.Interrupt() in a Catch Interruptexception Block
Lombok Annotations Do Not Compile Under Intellij Idea
Multi-Project Test Dependencies with Gradle
How to Force Selenium Webdriver to Click on Element Which Is Not Currently Visible
Sorting Arraylist in Alphabetical Order (Case Insensitive)
Jackson and Generic Type Reference
How to Inject Authenticationmanager Using Java Configuration in a Custom Filter
Does Setting Java Objects to Null Do Anything Anymore
Static Nested Class in Java, Why
How to Implement a Re-Try-Catch
Custom Button Not Working on MAC (Buttonui)
What Is the List of Valid @Suppresswarnings Warning Names in Java