2011-04-16 55 views

回答

642

在Java中,使用格式字符串轉換一個日期爲String:

// Create an instance of SimpleDateFormat used for formatting 
// the string representation of date (month/day/year) 
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); 

// Get the date today 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 reportDate = df.format(today); 

// Print what date is today! 
System.out.println("Report Date: " + reportDate); 

http://www.kodejava.org/examples/86.html

+21

爲什麼使用'Calendar'而不是普通'new Date()'?有區別嗎? – 2013-08-19 04:35:47

+8

注意:SimpleDateFormat不是線程安全的。 http://stackoverflow.com/questions/6840803/simpledateformat-thread-safety – Zags 2014-01-17 00:20:10

+1

答案中的格式與OP要求的格式不匹配。比它需要更復雜。 – Lukos 2014-01-30 10:40:52

6

它看起來像你正在尋找SimpleDateFormat

格式:YYYY-MM-DD KK:mm:ss的

+0

「kk」做了什麼特別的事嗎?我認爲埃裏克需要24小時。 – 2011-04-16 01:03:55

+2

是的,一天中的小時(1-24),但這可能不是OP所需要的。 'HH'(0-23)更常見。 – BalusC 2011-04-16 01:04:31

+1

@Cahrlie Salts kk從1-24開始,其中HH從0-23開始,而且假設他想要1-24 @BalusC DateFormat對象可以進行解析和格式化,這可能有點冒失。 – pickypg 2011-04-16 01:06:22

187
Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
String s = formatter.format(date); 
49

Commons-lang DateFormatUtils充滿了好東西(如果你的classpath中有commons-lang)

//Formats a date/time into a specific pattern 
DateFormatUtils.format(yourDate, "yyyy-MM-dd HH:mm:SS"); 
3
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; 
} 
8

你爲什麼不使用喬達(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 
+0

我建議還要傳遞一個DateTimeZone,而不是將JVM的當前默認時區分配給'DateTime'對象。 'new DateTime(currentDate,DateTimeZone.forID(「America/Montreal」))' – 2014-11-15 00:17:05

0
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 
} 
9

Altenative單行的純舊式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); 

這使用Formatterrelative indexing代替SimpleDateFormat這是不是線程安全的,順便說一句。

稍微重複一些,但只需要一條語句。 在某些情況下,這可能非常方便。

3

使用它的最簡單的方法是如下:

currentISODate = new Date().parse("yyyy-MM-dd'T'HH:mm:ss", "2013-04-14T16:11:48.000"); 

其中 「YYYY-MM-dd'T'HH:MM:SS」 是讀取日期

輸出的格式:太陽4月14日16時11分48秒EEST 2013

注:HH HH VS - HH指24小時時間格式 - HH指12小時的時間格式

+0

問題是關於相反的轉換。 – Vadzim 2016-08-06 03:06:46

2

如果喲你只需要從日期開始的時間,你可以使用String的特性。

Date test = new Date(); 
String dayString = test.toString(); 
String timeString = dayString.substring(11 , 19); 

這會自動剪切字符串的時間部分並將其保存在timeString中。

+0

這可能會破壞不同的區域設置。 – Vadzim 2016-08-06 03:06:22

0

讓我們試試這個

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; 
} 

Convert Date to String in Java

15

TL;博士

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.time類,現在取代了麻煩的舊的遺留日期時間類。

首先將您的java.util.Date轉換爲InstantInstant類表示UTC中時間軸上的一個時刻,分辨率爲nanoseconds(小數點後最多九位數字)。

轉換到/來自java.time的轉換是通過添加到舊類的新方法執行的。

Instant instant = myUtilDate.toInstant(); 

無論您java.util.Datejava.time.InstantUTC。如果你想看到UTC的日期和時間,就這樣吧。調用toString以標準ISO 8601格式生成字符串。

String output = instant.toString(); 

2014-11-14T14:05:09Z

對於其他格式,您需要將您Instant轉變爲更加靈活OffsetDateTime

OffsetDateTime odt = instant.atOffset(ZoneOffset.UTC); 

odt.toString():2014-11-14T14:05:09 + 00:00

得到一個字符串在你想要的格式,指定一個DateTimeFormatter。您可以指定一個自定義格式。但我會使用其中一個預定義的格式化程序(ISO_LOCAL_DATE_TIME),並用空格替換其輸出中的T

String output = odt.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) 
        .replace("T" , " "); 

2014年11月14日14時05分09秒

通過我不建議這樣的格式,你故意輸掉offset-from-UTC或時區信息的方式。對該字符串的日期時間值的含義產生歧義。

還要小心數據丟失,因爲在日期時間值的字符串表示中忽略(有效截斷)任何小數部分。

要通過某個特定區域的鏡頭wall-clock time看到同一時刻,請應用ZoneId以獲得ZonedDateTime

ZoneId z = ZoneId.of("America/Montreal"); 
ZonedDateTime zdt = instant.atZone(z); 

zdt.toString():2014-11-14T14:05:09-05:00 [美國/蒙特利爾]

要生成格式的字符串,執行與上述相同的但用zdt代替odt

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.time框架是建立在Java 8和更高版本。這些課程取代了麻煩的舊日期時間課程,如java.util.Date,.Calendar,& java.text.SimpleDateFormat

Joda-Time項目現在在maintenance mode中,建議遷移到java.time。請致電Oracle Tutorial。並搜索堆棧溢出了很多例子和解釋。

大部分的java.time功能後移植到Java 6 和ThreeTenABP還適於Android(見How to use…)。

ThreeTen-Extra項目擴展java.time與其他類。這個項目是未來可能增加java.time的一個試驗場。

+0

以下是使用Java 8 Time API進行格式設置的代碼示例:http://stackoverflow.com/a/43457343/603516 – Vadzim 2017-04-17 18:34:33

2

下面是使用新Java 8 Time API格式化legacyjava.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)。

List of predefined fomatters and pattern notation reference

現金

How to parse/format dates with LocalDateTime? (Java 8)

Java8 java.util.Date conversion to java.time.ZonedDateTime

Format Instant to String

What's the difference between java 8 ZonedDateTime and OffsetDateTime?

0

試試這個,

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 Help Centre

Date time example in java

0

在單發;)

要獲得日期

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()); 

編碼愉快:)

+0

僅供參考,麻煩的舊日期時間類,如['java.util.Date'](https: //docs.oracle.com/javase/9​​/docs/api/java/util/Date.html),['java.util.Calendar'](https://docs.oracle.com/javase/9​​/docs /api/java/util/Calendar.html)和'java.text.SimpleDateFormat'現在是[legacy](https://en.wikipedia.org/wiki/Legacy_system),由[java.time]代替( https://docs.oracle.com/javase/9​​/docs/api/java/time/package-summary.html)內置於Java 8和Java 9中的類。請參見[Oracle教程](https:// docs。 oracle.com/javase/tutorial/datetime/TOC.html)。 – 2018-02-04 05:37:50