[英]Convert java.util.Date to String
我想將java.util.Date
對象轉換為 Java 中的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);
Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = formatter.format(date);
Commons-lang DateFormatUtils充滿了好東西(如果你的類路徑中有 commons-lang)
//Formats a date/time into a specific pattern
DateFormatUtils.format(yourDate, "yyyy-MM-dd HH:mm:SS");
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
類表示UTC時間軸上的一個時刻,分辨率為納秒(最多九 (9) 位小數)。
與 java.time 的轉換由添加到舊類的新方法執行。
Instant instant = myUtilDate.toInstant();
您的java.util.Date
和java.time.Instant
都在UTC 中。 如果您想將日期和時間視為 UTC,那就這樣吧。 調用toString
以生成標准ISO 8601格式的字符串。
String output = instant.toString();
2014-11-14T14:05:09Z
對於其他格式,您需要將Instant
轉換為更靈活的OffsetDateTime
。
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );
odt.toString(): 2020-05-01T21:25:35.957Z
要獲得所需格式的字符串,請指定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[美國/蒙特利爾]
要生成格式化的字符串,請執行與上述相同的操作,但將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.
通過傳遞實例來應用該格式化程序。
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功能后移植到Java 6和7 ThreeTen,反向移植,並進一步用於安卓在ThreeTenABP (見如何使用...... )。
ThreeTen-Extra項目用額外的類擴展了 java.time。 該項目是未來可能添加到 java.time 的試驗場。
普通 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和相對索引而不是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
看起來您正在尋找SimpleDateFormat 。
格式:yyyy-MM-dd kk:mm:ss
單拍 ;)
獲取日期
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;
}
最簡單的使用方法如下:
currentISODate = new Date().parse("yyyy-MM-dd'T'HH:mm:ss", "2013-04-14T16:11:48.000");
其中“yyyy-MM-dd'T'HH:mm:ss”是閱讀日期的格式
輸出:2013 年 4 月 14 日星期日 16:11:48 EEST
注:HH vs hh - HH 指 24 小時時間格式 - hh 指 12 小時時間格式
如果您只需要日期中的時間,則可以使用 String 的功能。
Date test = new Date();
String dayString = test.toString();
String timeString = dayString.substring( 11 , 19 );
這將自動剪切 String 的時間部分並將其保存在timeString
。
以下是使用新的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
DateTimeFormatter
優點在於它可以被有效地緩存,因為它是線程安全的(與SimpleDateFormat
不同)。
學分:
如何使用 LocalDateTime 解析/格式化日期? (Java 8)
嘗試這個,
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 中日期和時間格式的更多信息,請參閱下面的鏈接
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
}
讓我們試試這個
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;
}
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
單線選項
這個選項可以簡單地用一行來寫出實際日期。
請注意,這是使用
Calendar.class
和SimpleDateFormat
,然后在 Java8 下使用它是不合邏輯的。
yourstringdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
Date date = new Date();
String strDate = String.format("%tY-%<tm-%<td %<tH:%<tM:%<tS", date);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.