I have this code snippet:
DateFormat formatter1;
formatter1 = new SimpleDateFormat("mm/DD/yyyy");
System.out.println((Date)formatter1.parse("08/16/2011"));
When I run this, I get this as the output:
Sun Jan 16 00:10:00 IST 2011
I expected:
Tue Aug 16 "Whatever Time" IST 2011
I mean to say I am not getting the month as expected. What is the mistake?
Method 1: Program to convert string to DateTime using datetime. strptime() function. strptime() is available in DateTime and time modules and is used for Date-Time Conversion. This function changes the given string of datetime into the desired format.
You can just use: Date yourDate = new Date(); SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); String date = DATE_FORMAT. format(yourDate);
Use the Date() constructor to convert a string to a Date object in TypeScript, e.g. const date = new Date('2024-07-21') . The Date() constructor takes a valid date string as a parameter and returns a Date object. Copied! We used the Date() constructor to convert a string to a Date object.
Try this:
new SimpleDateFormat("MM/dd/yyyy")
MM
is "month" (not mm
)dd
is "day" (not DD
)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!
m - min M - Months
Letter Date or Time Component Presentation Examples
G Era designator Text AD
y Year Year 1996; 96
M Month in year Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day in week Text Tuesday; Tue
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With