2011-04-16 81 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