繁体   English   中英

将 java.util.Date 转换为字符串

[英]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);

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

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

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.util.Date转换为Instant Instant类表示UTC时间轴上的一个时刻,分辨率为纳秒(最多九 (9) 位小数)。

与 java.time 的转换由添加到旧类的新方法执行。

Instant instant = myUtilDate.toInstant();

您的java.util.Datejava.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

在 IdeOne.com 上查看实时运行的代码

要获得所需格式的字符串,请指定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.time框架内置于 Java 8 及更高版本中。 这些类取代了麻烦的旧日期时间类,例如java.util.Date.Calendarjava.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)

Java8 java.util.Date 到 java.time.ZonedDateTime 的转换

将 Instant 格式化为字符串

java 8 ZonedDateTime 和 OffsetDateTime 有什么区别?

尝试这个,

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 中日期和时间格式的更多信息,请参阅下面的链接

甲骨文帮助中心

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

Java中日期到字符串的转换

    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.classSimpleDateFormat ,然后在 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM