繁体   English   中英

以yyyy-MM-dd hh.mm.ss格式获取当前日期时间

[英]get current date time in yyyy-MM-dd hh.mm.ss format

我有一个应用程序,它总是只在一个时区运行,所以我不需要担心时区之间的转换。 但是,必须始终按以下格式打印日期时间:

yyyy-MM-dd hh.mm.ss 

以下代码无法打印正确的格式:

public void setCreated(){
    DateTime now = new org.joda.time.DateTime();
    String pattern = "yyyy-MM-dd hh.mm.ss";
    created  = DateTime.parse(now.toString(), DateTimeFormat.forPattern(pattern));
    System.out.println("''''''''''''''''''''''''''' created is: "+created);
}  

setCreated()方法产生以下输出:

"2013-12-16T20:06:18.672-08:00"

如何更改setCreated()中的代码,以便打印出以下代码:

"2013-12-16 20:06:18"

你没有解析任何东西,你正在格式化它。 您需要使用DateTimeFormatter#print(ReadableInstant)

DateTime now = new org.joda.time.DateTime();
String pattern = "yyyy-MM-dd hh.mm.ss";
DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern);
String formatted = formatter.print(now);
System.out.println(formatted);

打印

2013-12-16 11.13.24

这与您的格式不符,但我的基础是您的代码,而不是您的预期输出。

 public static void main(String args[])
{

SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//dd/MM/yyyy
Date now = new Date();
String strDate = sdfDate.format(now);
    System.out.println(strDate);
}

2013-12-17 09:48:11

尝试这个

        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss");
        Date now = new Date();
        String strDate = sdfDate.format(now);
        System.out.println(strDate);

演示

尝试这个:

org.joda.time.DateTime now = new org.joda.time.DateTime();
String pattern = "yyyy-MM-dd hh.mm.ss";
DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern);
String formatted = formatter.print(now);
LocalDateTime date = formatter.parseLocalDateTime(formatted);
System.out.println(date.toDateTime());

现在在Java 9中,您可以使用:

LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh.mm.ss"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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