nov*_*rmr 395 java formatting date java.util.date
我想将java.util.Date
对象转换为String
Java中的对象.
格式是 2010-05-30 22:15:52
Ali*_*oud 740
转换日期为字符串使用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);
Run Code Online (Sandbox Code Playgroud)
来自http://www.kodejava.org/examples/86.html
Cha*_*lts 217
Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = formatter.format(date);
Run Code Online (Sandbox Code Playgroud)
web*_*pat 62
Commons-lang DateFormatUtils充满了好东西(如果你的类路径中有公共语言)
//Formats a date/time into a specific pattern
DateFormatUtils.format(yourDate, "yyyy-MM-dd HH:mm:SS");
Run Code Online (Sandbox Code Playgroud)
Bas*_*que 21
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.
Run Code Online (Sandbox Code Playgroud)
2014-11-14 14:05:09
现代的方法是使用java.time类,它们现在取代了麻烦的旧遗留日期时间类.
首先转换java.util.Date
为Instant
.该Instant
级表示时间轴上的时刻UTC,分辨率为纳秒(最多9个(9)小数的位数).
来自/来自java.time的转换是通过添加到旧类的新方法来执行的.
Instant instant = myUtilDate.toInstant();
Run Code Online (Sandbox Code Playgroud)
你java.util.Date
和你java.time.Instant
都是UTC.如果您希望将日期和时间视为UTC,那么就这样吧.调用toString
以标准ISO 8601格式生成String .
String output = instant.toString();
Run Code Online (Sandbox Code Playgroud)
2014-11-14T14:05:09Z
对于其他格式,您需要将您Instant
转变为更灵活的OffsetDateTime
.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );
Run Code Online (Sandbox Code Playgroud)
odt.toString():2014-11-14T14:05:09 + 00:00
要获得所需格式的String,请指定DateTimeFormatter
.您可以指定自定义格式.但我会使用其中一个预定义的formatters(ISO_LOCAL_DATE_TIME
),并用T
SPACE 替换其输出.
String output = odt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " );
Run Code Online (Sandbox Code Playgroud)
2014-11-14 14:05:09
顺便说一句,我不推荐这种格式,你故意丢失从UTC或时区的偏移信息.创建关于该字符串的日期时间值的含义的歧义.
还要注意数据丢失,因为在String的日期时间值表示中忽略(有效截断)任何小数秒.
要通过某个特定区域的挂钟时间镜头看到相同的时刻,请应用a ZoneId
来获得a ZonedDateTime
.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
Run Code Online (Sandbox Code Playgroud)
zdt.toString():2014-11-14T14:05:09-05:00 [美国/蒙特利尔]
要生成格式化的String,请执行与上面相同的操作,但替换odt
为zdt
.
String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " );
Run Code Online (Sandbox Code Playgroud)
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.
Run Code Online (Sandbox Code Playgroud)
通过传递实例来应用该格式化程序.
String output = zdt.format( f );
Run Code Online (Sandbox Code Playgroud)
该java.time框架是建立在Java 8和更高版本.这些类取代的麻烦旧日期,时间类,如java.util.Date
,.Calendar
,和java.text.SimpleDateFormat
.
现在处于维护模式的Joda-Time项目建议迁移到java.time.
要了解更多信息,请参阅Oracle教程.并搜索Stack Overflow以获取许多示例和解释.
大部分的java.time功能后移植到Java 6和7 ThreeTen,反向移植,并进一步适应的Android在ThreeTenABP(见如何使用......).
该ThreeTen-额外项目与其他类扩展java.time.该项目是未来可能添加到java.time的试验场.
Vad*_*zim 15
普通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);
Run Code Online (Sandbox Code Playgroud)
它使用格式化和相关的索引,而不是SimpleDateFormat
它不是线程安全的,顺便说一句.
稍微多一点重复但只需要一个陈述.在某些情况下这可能很方便.
你为什么不用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
Run Code Online (Sandbox Code Playgroud)
小智 5
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;
}
Run Code Online (Sandbox Code Playgroud)
以下是使用新的Java 8 Time API格式化旧版 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
Run Code Online (Sandbox Code Playgroud)
它的优点是DateTimeFormatter
它可以被有效地缓存,因为它是线程安全的(与 不同SimpleDateFormat
)。
学分:
如何使用 LocalDateTime 解析/格式化日期?(Java 8)
Java8 java.util.Date 转换为 java.time.ZonedDateTime
java 8 ZonedDateTime 和 OffsetDateTime 有什么区别?
单发;)
获取日期
String date = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
Run Code Online (Sandbox Code Playgroud)
争取时间
String time = new SimpleDateFormat("hh:mm", Locale.getDefault()).format(new Date());
Run Code Online (Sandbox Code Playgroud)
获取日期和时间
String dateTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefaut()).format(new Date());
Run Code Online (Sandbox Code Playgroud)
快乐的编码:)
归档时间: |
|
查看次数: |
1102393 次 |
最近记录: |