我想在Java中把java.util.Date
对象转换为String
。
其格式为2010-05-30 22:15:52
。
使用DateFormat#format
方法将一个日期转换成**字符串。
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);
来自http://www.kodejava.org/examples/86.html
myUtilDate.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
现代的方法是使用java.time类,它现在取代了麻烦的旧日期-时间类。
首先将你的java.util.Date
转换为Instant
。
Instant
](http://docs.oracle.com/javase/8/docs/api/java/time/Instant.html)类以[UTC](https://en.wikipedia.org/wiki/Coordinated_Universal_Time)表示时间轴上的一个时刻,其分辨率为[纳秒](https://en.wikipedia.org/wiki/Nanosecond)(最多为小数点后的九(9)位)。
java.time与java.time之间的转换由添加到旧类中的新方法来完成。
Instant instant = myUtilDate.toInstant();
你的java.util.Date
和java.time.Instant
都是以UTC为单位。
如果你想把日期和时间看成UTC,那就这样吧。
调用toString
生成一个标准[ISO 8601][2]格式的字符串。
String output = instant.toString();
2014-11-14T14:05:09Z
对于其他格式,您需要将Instant
转换为更灵活的[OffsetDateTime
][3]。
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );
odt.toString()。 2014-11-14T14:05:09+00:00
要想得到一个你所需格式的字符串,请指定一个[DateTimeFormatter
][4]。
你可以指定一个自定义的格式。
但我会使用一个预定义的格式([ISO_LOCAL_DATE_TIME
][5]),并在其输出中用空格代替T
。
String output = odt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " );
2014-11-14 14:05:09
对了,我不推荐这种故意丢失[offset-from-UTC][6]或时区信息的格式。 对该字符串的日期-时间值的含义产生歧义。
同时也要小心数据丢失,因为在你的String的日期-时间值表示中,任何小数点的秒都会被忽略(有效地截断)。
如果要通过某个特定区域的[挂钟时间][7]来查看同一时刻,可以应用一个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" , " " );
2014-11-14 14:05:09
如果执行这段代码的次数非常多,你可能想提高效率,避免调用String::replace
。
丢掉这个调用也会让你的代码更短。
如果需要,可以在自己的DateTimeFormatter
对象中指定自己的格式化模式。
将这个实例缓存为一个常量或成员,以便重用。
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ); // Data-loss: Dropping any fractional second.
通过传递实例来应用该formatter。
String output = zdt.format( f );
java.time框架内置于Java 8及更新版本中。
这些类取代了麻烦的旧的日期-时间类,如java.util.Date
、.Calendar
、&
java.text.SimpleDateFormat
。
Joda-Time](http://www.joda.org/joda-time/)项目,现在处于[维护模式](https://en.wikipedia.org/wiki/Maintenance_mode),建议迁移到java.time。
要了解更多,请看Oracle教程。 并在Stack Overflow中搜索许多例子和解释。
java.time的大部分功能都回移植到了Java 6 &.7中。 7的ThreeTen-Backport,并在ThreeTenABP中进一步适配到Android(参见如何使用...)。
ThreeTen-Extra](http://www.threeten.org/threeten-extra/)项目扩展了java.time的附加类。 这个项目是对java.time未来可能增加的类的一个试验场。
1:
[2]: https://en.wikipedia.org/wiki/ISO_8601 [3]: http://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html [4]: http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html [5]: https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_LOCAL_DATE_TIME [6]: https://en.wikipedia.org/wiki/UTC_offset [7]: https://en.wikipedia.org/wiki/Wall-clock_time
Altenative one-liners in plain-old 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);
这使用了[Formatter][1]和[relative indexing][2],而不是使用[非线程安全][3]的 "SimpleDateFormat"。
略显重复,但只需要一条语句。 这在某些情况下可能很方便。
[1]: https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#dt [2]: https://stackoverflow.com/questions/6891175/what-about-if-youve-got-the-same-parameter-multiple-times-in-string-format/41150461#41150461 [3]: https://stackoverflow.com/questions/4021151/java-dateformat-is-not-threadsafe-what-does-this-leads-to
在一次拍摄中;)
获取日期
String 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());
编码快乐:)
public 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;
}
下面是使用新的[Java 8 Time API][1]来格式化[legacy][2]java.util.Date
的例子。
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS Z")
.withZone(ZoneOffset.UTC);
String utcFormatted = formatter.format(date.toInstant());
ZonedDateTime utcDatetime = date.toInstant().atZone(ZoneOffset.UTC);
String utcFormatted2 = utcDatetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS Z"));
// gives the same as above
ZonedDateTime localDatetime = date.toInstant().atZone(ZoneId.systemDefault());
String localFormatted = localDatetime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME);
// 2011-12-03T10:15:30+01:00[Europe/Paris]
String nowFormatted = LocalDateTime.now().toString(); // 2007-12-03T10:15:30.123
DateTimeFormatter
的好处是,它可以有效地缓存,因为它是线程安全的(不像SimpleDateFormat
)。
[预定义fomatters列表和模式符号参考][3]。
信用。
https://stackoverflow.com/questions/22463062/how-to-parse-format-dates-with-localdatetime-java-8
https://stackoverflow.com/questions/25229124/format-instant-to-string
[1]: http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html [2]: https://docs.oracle.com/javase/tutorial/datetime/iso/legacy.html [3]: [3]:https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#predefined
试试这个
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class Date
{
public static void main(String[] args)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = "2013-05-14 17:07:21";
try
{
java.util.Date dt = sdf.parse(strDate);
System.out.println(sdf.format(dt));
}
catch (ParseException pe)
{
pe.printStackTrace();
}
}
}
产出:
2013-05-14 17:07:21
更多关于java中的日期和时间格式化,请参考以下链接
[Oracle帮助中心][1]
[java中的日期时间示例][2]
[1]: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html [2]: https://www.flowerbrackets.com/java-date-to-string/
public static void main(String[] args)
{
Date d = new Date();
SimpleDateFormat form = new SimpleDateFormat("dd-mm-yyyy hh:mm:ss");
System.out.println(form.format(d));
String str = form.format(d); // or if you want to save it in String str
System.out.println(str); // and print after that
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = "2010-05-30 22:15:52";
java.util.Date formatedDate = sdf.parse(date); // returns a String when it is parsed
System.out.println(sdf.format(formatedDate)); // the use of format function returns a String
试试这个
public static void main(String args[]) {
Calendar cal = GregorianCalendar.getInstance();
Date today = cal.getTime();
DateFormat df7 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
String str7 = df7.format(today);
System.out.println("String in yyyy-MM-dd format is: " + str7);
} catch (Exception ex) {
ex.printStackTrace();
}
}
或效用函数
public String convertDateToString(Date date, String format) {
String dateStr = null;
DateFormat df = new SimpleDateFormat(format);
try {
dateStr = df.format(date);
} catch (Exception ex) {
ex.printStackTrace();
}
return dateStr;
}
从[在Java中转换日期为字符串][1]
[1]: http://javabycode.com/java-core/java-common/convert-date-to-string-in-java.html
单行选择
这个选项得到了一个简单的单行来写实际日期。
请注意,这是用
Calendar.class
和SimpleDateFormat
,然后它不是 >。 在Java8下使用它是符合逻辑的。
yourstringdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());