我想在Java中将java.util.Date
对象转换为String
。
格式为2010-05-30 22:15:52
我想在Java中将java.util.Date
对象转换为String
。
格式为2010-05-30 22:15:52
使用DateFormat#format
方法将 Date 转换为 String:
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);
Calendar
而不是简单的 new Date()
?它们有区别吗? - Alexander MalakhovFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = formatter.format(date);
如果您的类路径中包含commons-lang,那么DateFormatUtils是一个非常好用的工具库。
//Formats a date/time into a specific pattern
DateFormatUtils.format(yourDate, "yyyy-MM-dd HH:mm:SS");
null
检查。 - Farrukh ChishtimyUtilDate.toInstant() // Convert `java.util.Date` to `Instant`.
.atOffset( ZoneOffset.UTC ) // Transform `Instant` to `OffsetDateTime`.
.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ) // Generate a String.
.replace( "T" , " " ) // Put a SPACE in the middle.
2014年11月14日14:05:09
Instant instant = myUtilDate.toInstant();
java.util.Date
和java.time.Instant
都在UTC中。如果你想以UTC格式查看日期和时间,那就这么做吧。调用toString
方法生成符合ISO 8601标准格式的字符串。String output = instant.toString();
2014年11月14日14:05:09 UTC时间
对于其他格式,您需要将Instant
转换为更灵活的OffsetDateTime
。
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );
odt.toString(): 2020-05-01T21:25:35.957Z
请查看 IdeOne.com 上的代码实时运行。
要获得所需格式的字符串,请指定DateTimeFormatter
。您可以指定自定义格式,但我建议使用预定义的格式之一(ISO_LOCAL_DATE_TIME
),并将其输出中的T
替换为空格。
String output = odt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " );
2014年11月14日14:05:09
顺便提一下,我不建议使用这种格式,其中故意丢失偏移量-来自UTC或时区信息。这会导致该字符串的日期时间值的含义不明确。
此外,要注意数据丢失,因为你的字符串表示的日期时间值忽略了任何小数秒(实际上被截断了)。
要通过某个特定地区的挂钟时间观察同一时刻,请应用ZoneId
获取ZonedDateTime
。
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
zdt.toString(): 2014-11-14T14:05:09-05:00[America/Montreal]
为了生成格式化的字符串,做法与上面相同,只需将odt
替换为zdt
即可。
String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " );
String::replace
。去掉这个调用也会使您的代码更短。如果需要,可以在自己的 DateTimeFormatter
对象中指定自己的格式化模式。将此实例缓存为常量或成员以便重用。DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ); // Data-loss: Dropping any fractional second.
通过传递该实例来应用该格式化程序。
String output = zdt.format( f );
java.time框架内置于Java 8及更高版本中。这些类替代了老旧的日期时间类,如java.util.Date
, .Calendar
, 和java.text.SimpleDateFormat
。
Joda-Time项目现在处于维护模式,建议迁移到java.time。
要了解更多信息,请参阅Oracle教程。并在Stack Overflow上搜索许多示例和解释。
许多java.time功能在ThreeTen-Backport中向Java 6和7回溯,并在ThreeTenABP中进一步适应Android(请参见如何使用...)。 ThreeTen-Extra项目通过添加额外的类来扩展java.time。该项目是java.time可能未来添加的潜在试验场。Z
而不是 +00:00
。我已经修改了回答,谢谢。FYI,它们的含义相同:Z
,发音为“Zulu”,表示零小时-分钟-秒的偏移量,与 +00:00
相同。 [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)标准支持这两种样式。 - Basil BourqueInstant
类中确实有一个atOffset
方法。请参阅Javadoc:Instant::atOffset
。在Java 8中,像Instant.now().atOffset( ZoneOffset.UTC ).toString()
这样的调用将运行。检查您的import
语句。验证您的IDE /项目设置为运行Java 8或更高版本,而不是早期版本的Java。在IdeOne.com上查看代码实时运行:https://ideone.com/2Vm2O5 - Basil Bourque普通Java中的备选一行代码:
String.format("The date: %tY-%tm-%td", date, date, date);
String.format("The date: %1$tY-%1$tm-%1$td", date);
String.format("Time with tz: %tY-%<tm-%<td %<tH:%<tM:%<tS.%<tL%<tz", date);
String.format("The date and time in ISO format: %tF %<tT", date);
import java.util.Date;
并声明 Date date= new Date();
以使此代码示例完整。如果从问题中还不明显的话。 - AmigoJack为什么不使用Joda (org.joda.time.DateTime)呢? 它基本上是一个一行代码。
Date currentDate = GregorianCalendar.getInstance().getTime();
String output = new DateTime( currentDate ).toString("yyyy-MM-dd HH:mm:ss");
// output: 2014-11-14 14:05:09
DateTime
对象。new DateTime(currentDate, DateTimeZone.forID("America/Montreal"))
- Basil BourqueString date = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
获取时间
String time = new SimpleDateFormat("hh:mm", Locale.getDefault()).format(new Date());
获取日期和时间
String dateTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefaut()).format(new Date());
愉快的编程 :)
java.util.Date
、java.util.Calendar
和java.text.SimpleDateFormat
之类令人头疼的旧日期时间类现在已经过时,被内置于Java 8和Java 9中的java.time类所取代。请参见Oracle的教程。 - Basil Bourque看起来你正在寻找SimpleDateFormat。
格式:yyyy-MM-dd kk:mm:ss
HH
(0-23)更为常见。 - BalusCpublic static String formateDate(String dateString) {
Date date;
String formattedDate = "";
try {
date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss",Locale.getDefault()).parse(dateString);
formattedDate = new SimpleDateFormat("dd/MM/yyyy",Locale.getDefault()).format(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return formattedDate;
}
Date test = new Date();
String dayString = test.toString();
String timeString = dayString.substring( 11 , 19 );
这将自动切掉字符串的时间部分,并将其保存在timeString
中。
Date
类。该类设计不佳且已经过时。相反,使用Instant
或来自java.time,现代Java日期和时间API的其他类。 - Ole V.V.