更改Java字符串中的日期格式
我有String代表约会。
String date_s = "2011-01-18 00:00:00.0";
我想将其转换为02011-00-1并以2011-01-18格式输出。
2011-01-18
我怎样才能做到这一点?
好的,根据我在下面找到的答案,这是我尝试过的东西:
String date_s = " 2011-01-18 00:00:00.0";
SimpleDateFormat dt = new SimpleDateFormat("yyyyy-mm-dd hh:mm:ss");
Date date = dt.parse(date_s);
SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd");
System.out.println(dt1.format(date));
但它输出02011-00-1而不是所需的2011-01-18.我做错了什么?
16个解决方案
470 votes
使用M(如果字符串碰巧包含时区部分,则为M)以某种模式将M解析为m。
String oldstring = "2011-01-18 00:00:00.0";
LocalDateTime datetime = LocalDateTime.parse(oldstring, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"));
使用M(或M)以特定模式将M格式化为m。
String newstring = datetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
System.out.println(newstring); // 2011-01-18
或者,当您还没有使用Java 8时,请使用M以某种模式将M解析为m。
String oldstring = "2011-01-18 00:00:00.0";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(oldstring);
使用M以特定模式将M格式化为m。
String newstring = new SimpleDateFormat("yyyy-MM-dd").format(date);
System.out.println(newstring); // 2011-01-18
也可以看看:
Java字符串到日期转换
更新:根据您的失败尝试:模式区分大小写。 阅读M javadoc各个部分代表什么。 代表例如M持续数月和m持续数分钟。 此外,存在四位数的年份yyyy,而不是五位yyyyy。仔细看看我在上面发布的代码片段。
BalusC answered 2019-01-06T06:53:32Z
137 votes
格式化是CASE-SENSITIVE所以使用MM的月份不是mm(这是分钟)和yyyy如需参考,您可以使用以下备忘单。
G Era designator Text AD
y Year Year 1996; 96
Y Week year Year 2009; 09
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 name in week Text Tuesday; Tue
u Day number of week (1 = Monday, ..., 7 = Sunday) Number 1
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
X Time zone ISO 8601 time zone -08; -0800; -08:00
例子:
"yyyy.MM.dd G 'at' HH:mm:ss z" 2001.07.04 AD at 12:08:56 PDT
"EEE, MMM d, ''yy" Wed, Jul 4, '01
"h:mm a" 12:08 PM
"hh 'o''clock' a, zzzz" 12 o'clock PM, Pacific Daylight Time
"K:mm a, z" 0:08 PM, PDT
"yyyyy.MMMMM.dd GGG hh:mm aaa" 02001.July.04 AD 12:08 PM
"EEE, d MMM yyyy HH:mm:ss Z" Wed, 4 Jul 2001 12:08:56 -0700
"yyMMddHHmmssZ" 010704120856-0700
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" 2001-07-04T12:08:56.235-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX" 2001-07-04T12:08:56.235-07:00
"YYYY-'W'ww-u" 2001-W27-3
Dev answered 2019-01-06T06:54:00Z
104 votes
答案当然是创建一个SimpleDateFormat对象并使用它来将字符串解析为Date并将Dates格式化为字符串。 如果你已经尝试过SimpleDateFormat并且它不起作用,那么请显示你的代码以及你可能收到的任何错误。
附录:格式为String的“mm”与“MM”不同。 使用MM数月,mm使用数分钟。 而且,yyyyy与yyyy不同。 例如。,:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class FormateDate {
public static void main(String[] args) throws ParseException {
String date_s = "2011-01-18 00:00:00.0";
// *** note that it's "yyyy-MM-dd hh:mm:ss" not "yyyy-mm-dd hh:mm:ss"
SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = dt.parse(date_s);
// *** same for the format String below
SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(dt1.format(date));
}
}
Hovercraft Full Of Eels answered 2019-01-06T06:54:32Z
19 votes
为什么不简单地使用它
Date convertToDate(String receivedDate) throws ParseException{
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Date date = formatter.parse(receivedDate);
return date;
}
另外,这是另一种方式:
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String requiredDate = df.format(new Date()).toString();
要么
Date requiredDate = df.format(new Date());
干杯!
89n3ur0n answered 2019-01-06T06:55:05Z
15 votes
在Java 8及更高版本中使用java.time软件包:
String date = "2011-01-18 00:00:00.0";
TemporalAccessor temporal = DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss.S")
.parse(date); // use parse(date, LocalDateTime::from) to get LocalDateTime
String output = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(temporal);
Vitalii Fedorenko answered 2019-01-06T06:55:28Z
9 votes
[编辑包括BalusC的更正]SimpleDateFormat类应该可以解决这个问题:
String pattern = "yyyy-MM-dd HH:mm:ss.S";
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
Date date = format.parse("2011-01-18 00:00:00.0");
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
Bryan answered 2019-01-06T06:55:50Z
9 votes
请在此处参阅“日期和时间模式”。[http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html]
import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.ParseException;
public class DateConversionExample{
public static void main(String arg[]){
try{
SimpleDateFormat sourceDateFormat = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");
Date date = sourceDateFormat.parse("2011-01-18 00:00:00.0");
SimpleDateFormat targetDateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(targetDateFormat.format(date));
}catch(ParseException e){
e.printStackTrace();
}
}
}
Touchstone answered 2019-01-06T06:56:12Z
8 votes
try
{
String date_s = "2011-01-18 00:00:00.0";
SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
Date tempDate=simpledateformat.parse(date_s);
SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Output date is = "+outputDateFormat.format(tempDate));
} catch (ParseException ex)
{
System.out.println("Parse Exception");
}
Fathah Rehman P answered 2019-01-06T06:56:28Z
8 votes
public class SystemDateTest {
String stringDate;
public static void main(String[] args) {
SystemDateTest systemDateTest = new SystemDateTest();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-mm-yyyy hh:mm:ss");
systemDateTest.setStringDate(simpleDateFormat.format(systemDateTest.getDate()));
System.out.println(systemDateTest.getStringDate());
}
public Date getDate() {
return new Date();
}
public String getStringDate() {
return stringDate;
}
public void setStringDate(String stringDate) {
this.stringDate = stringDate;
}
}
Neeraj Gahlawat answered 2019-01-06T06:56:44Z
7 votes
其他答案是正确的,基本上你的模式中有“y”字符错误。
时区
还有一个问题......你没有解决时区问题。 如果您打算使用UTC,那么您应该这样说。 如果没有,答案就不完整了。 如果您想要的只是没有时间的日期部分,那么没有问题。 但是如果你做了可能涉及时间的进一步工作,那么你应该指定一个时区。
乔达时间
这是相同类型的代码,但使用第三方开源Joda-Time 2.3库
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
String date_s = "2011-01-18 00:00:00.0";
org.joda.time.format.DateTimeFormatter formatter = org.joda.time.format.DateTimeFormat.forPattern( "yyyy-MM-dd' 'HH:mm:ss.SSS" );
// By the way, if your date-time string conformed strictly to ISO 8601 including a 'T' rather than a SPACE ' ', you could
// use a formatter built into Joda-Time rather than specify your own: ISODateTimeFormat.dateHourMinuteSecondFraction().
// Like this:
//org.joda.time.DateTime dateTimeInUTC = org.joda.time.format.ISODateTimeFormat.dateHourMinuteSecondFraction().withZoneUTC().parseDateTime( date_s );
// Assuming the date-time string was meant to be in UTC (no time zone offset).
org.joda.time.DateTime dateTimeInUTC = formatter.withZoneUTC().parseDateTime( date_s );
System.out.println( "dateTimeInUTC: " + dateTimeInUTC );
System.out.println( "dateTimeInUTC (date only): " + org.joda.time.format.ISODateTimeFormat.date().print( dateTimeInUTC ) );
System.out.println( "" ); // blank line.
// Assuming the date-time string was meant to be in Kolkata time zone (formerly known as Calcutta). Offset is +5:30 from UTC (note the half-hour).
org.joda.time.DateTimeZone kolkataTimeZone = org.joda.time.DateTimeZone.forID( "Asia/Kolkata" );
org.joda.time.DateTime dateTimeInKolkata = formatter.withZone( kolkataTimeZone ).parseDateTime( date_s );
System.out.println( "dateTimeInKolkata: " + dateTimeInKolkata );
System.out.println( "dateTimeInKolkata (date only): " + org.joda.time.format.ISODateTimeFormat.date().print( dateTimeInKolkata ) );
// This date-time in Kolkata is a different point in the time line of the Universe than the dateTimeInUTC instance created above. The date is even different.
System.out.println( "dateTimeInKolkata adjusted to UTC: " + dateTimeInKolkata.toDateTime( org.joda.time.DateTimeZone.UTC ) );
跑的时候......
dateTimeInUTC: 2011-01-18T00:00:00.000Z
dateTimeInUTC (date only): 2011-01-18
dateTimeInKolkata: 2011-01-18T00:00:00.000+05:30
dateTimeInKolkata (date only): 2011-01-18
dateTimeInKolkata adjusted to UTC: 2011-01-17T18:30:00.000Z
Basil Bourque answered 2019-01-06T06:57:42Z
6 votes
String str = "2000-12-12";
Date dt = null;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
try
{
dt = formatter.parse(str);
}
catch (Exception e)
{
}
JOptionPane.showMessageDialog(null, formatter.format(dt));
Eren answered 2019-01-06T06:57:58Z
5 votes
你也可以使用substring()
String date_s = "2011-01-18 00:00:00.0";
date_s.substring(0,10);
如果您想在日期前面留出空格,请使用
String date_s = " 2011-01-18 00:00:00.0";
date_s.substring(1,11);
Martin answered 2019-01-06T06:58:27Z
5 votes
你可以使用:
Date yourDate = new Date();
SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
String date = DATE_FORMAT.format(yourDate);
它完美地运作!
chŝdk answered 2019-01-06T06:58:57Z
4 votes
private SimpleDateFormat dataFormat = new SimpleDateFormat("dd/MM/yyyy");
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if(value instanceof Date) {
value = dataFormat.format(value);
}
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
};
user2632575 answered 2019-01-06T06:59:12Z
3 votes
删除一个y表单SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd");应该是SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-mm-dd");
Pankaj Sharma answered 2019-01-06T06:59:35Z
3 votes
你可以试试java 8 new date,可以在oracle文档中找到更多信息。
或者你可以尝试旧的
public static Date getDateFromString(String format, String dateStr) {
DateFormat formatter = new SimpleDateFormat(format);
Date date = null;
try {
date = (Date) formatter.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
public static String getDate(Date date, String dateFormat) {
DateFormat formatter = new SimpleDateFormat(dateFormat);
return formatter.format(date);
}
Ran Adler answered 2019-01-06T07:00:04Z