问题
Hi I am trying to get today's date but not getting proper output
import java.text.DateFormat;
import java.text.SimpleDateFormat;
private static final DateFormat sdf = new SimpleDateFormat("DD/MM/YYYY");
System.out.println("TODAY :" + sdf.format(new Date()));
output
TODAY :142/05/2017
Year and month coming properly but why the day is coming like this
回答1:
D
is Day in year
d
is Day in month
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
EDIT: Also as @JeremyP noticed you can use yyyy
for getting year 'cause
Y
is Week year
回答2:
Oracle:
SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date -> text), parsing (text -> date), and normalization.
- simple y Year -Year (1996; 96)
capital Y Week year -Year (2009; 09)
simple d Day in month -Number (10)
capital D Day in year -Number (189)
capital M Month in year -Month (July; Jul; 07)
In your code:
SimpleDateFormat("DD/MM/YYYY")
Should be:
SimpleDateFormat("dd/MM/yyyy")
refer documentation for more info
回答3:
According to the javadocs
D
is for the day in the year and Y
is for the week year.
You need to use d
(lower case) for Day in month
and y
(lower case) for Year
This you pattern should look like:
DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
回答4:
Replace DD
with dd
and YYYY
to yyyy
. MM is in capital and others are in lowercase.
d = day of the month
D = day of the year
M = month in year
m = minute in hour
y = Year
Y = Week year
private static final DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
System.out.println("TODAY :" + sdf.format(new Date()));
来源:https://stackoverflow.com/questions/44110668/how-to-format-todays-day-with-simpledateformat