2012-09-26 84 views
0

我想在我選擇的區域中以特定格式(例如HH-MM-SS,MM-DD-YY,MoMo-DD-YY-HH-MM-SS等)獲取當前日期時間。 如何使用JodaTime來做到這一點?如何獲取特定格式的當前時間?

+1

你有什麼試過?您可以使用'DateTime'構造函數輕鬆獲取特定區域中的當前時間,並且可以使用'DateTimeFormat'將其格式化爲特定格式。你卡在哪裏? –

+0

@JonSkeet - 我可以製作帶有區域的DateTime(DT)。不知道哪個更好 - DateTimeZone.forID(XXXX)或DateTime(TheZone)。在這一步之後,我如何將獲得的DT i轉換成特定的格式? –

回答

3

既然你已經看到了用戶指南(包括上time zonesformatting部分),其中你的困惑是不是真的清楚。一些示例代碼,讓你去:

DateTimeZone zone = DateTimeZone.forID("Europe/London"); 
DateTime currentTimeInLondon = new DateTime(zone); 
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm:ss, MM-dd-yyyy"); 
String text = formatter.print(currentTimeInLondon); // e.g. 08:24:54, 09-26-2012 

這將是值得你花一些時間來分析爲什麼你不能得到這個代碼自己,給予用戶指南中的信息。能夠解決如何使用API​​是軟件工程師的一項非常重要的技能 - 您不可以一直指望使用API​​。

+0

是的,我看到了。它也適用於YourDateTime.toString(「PutALegalFormatHere」); –

+0

@davidblaine:是的,但通常並不乾淨 - 特別是,您通常可以創建一個DateTimeFormat * *並在整個應用程序生命週期中重用它。 –

1

使用以下代碼根據特定區域的格式獲取時間。

Locale locale = Locale.FRENCH; 

    // Format with a custom format 
    DateFormat formatter = new SimpleDateFormat("E, dd MMM yyyy", locale); 
    String s = formatter.format(new Date()); 
    // mar., 29 sept. 2012 

    // Format with a default format 
    s = DateFormat.getDateInstance(DateFormat.MEDIUM, locale).format(new Date()); 
    // 29 sept. 2012 
+0

約達時間請。 –

+0

檢查出喬達時間的鏈接。 http://stackoverflow.com/questions/10106143/work-around-for-a-joda-time-bug-in-periodformat –

相關問題