[英]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.