回答
在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);
它看起來像你正在尋找SimpleDateFormat。
格式:YYYY-MM-DD KK:mm:ss的
Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = formatter.format(date);
Commons-lang DateFormatUtils充滿了好東西(如果你的classpath中有commons-lang)
//Formats a date/time into a specific pattern
DateFormatUtils.format(yourDate, "yyyy-MM-dd HH:mm:SS");
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;
}
你爲什麼不使用喬達(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
我建議還要傳遞一個DateTimeZone,而不是將JVM的當前默認時區分配給'DateTime'對象。 'new DateTime(currentDate,DateTimeZone.forID(「America/Montreal」))' – 2014-11-15 00:17:05
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
}
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);
這使用Formatter和relative indexing代替SimpleDateFormat
這是不是線程安全的,順便說一句。
稍微重複一些,但只需要一條語句。 在某些情況下,這可能非常方便。
使用它的最簡單的方法是如下:
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小時的時間格式
問題是關於相反的轉換。 – Vadzim 2016-08-06 03:06:46
如果喲你只需要從日期開始的時間,你可以使用String的特性。
Date test = new Date();
String dayString = test.toString();
String timeString = dayString.substring(11 , 19);
這會自動剪切字符串的時間部分並將其保存在timeString
中。
這可能會破壞不同的區域設置。 – Vadzim 2016-08-06 03:06:22
讓我們試試這個
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;
}
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
轉換爲Instant
。 Instant
類表示UTC中時間軸上的一個時刻,分辨率爲nanoseconds(小數點後最多九位數字)。
轉換到/來自java.time的轉換是通過添加到舊類的新方法執行的。
Instant instant = myUtilDate.toInstant();
無論您java.util.Date
和java.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():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的一個試驗場。
以下是使用Java 8 Time API進行格式設置的代碼示例:http://stackoverflow.com/a/43457343/603516 – Vadzim 2017-04-17 18:34:33
下面是使用新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
What's the difference between java 8 ZonedDateTime and 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格式請參考以下鏈接
在單發;)
要獲得日期
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());
編碼愉快:)
僅供參考,麻煩的舊日期時間類,如['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
- 1. 轉換字符串java.util.Date的
- 2. 如何java.util.Date轉換爲字符串
- 3. NSDate日期字符串轉換爲java.util.date
- 4. 轉換DSTREAM [java.util.Date]到DSTREAM [字符串]
- 5. 使用EL將java.util.Date值轉換爲字符串使用EL
- 6. 如何將時間戳字符串轉換爲java.util.Date
- 7. 將字符串轉換爲java中的java.util.date格式
- 8. 將字符串轉換爲字符串
- 9. 將字符串轉換爲字符串
- 10. 將字符串轉換爲字符串
- 11. 將java.time.temporal.Temporal轉換爲java.util.Date
- 12. 將java.sql.Date&java.util.Date轉換爲org.joda.time.LocalDate
- 13. 將java.sql.Date轉換爲java.util.Date
- 14. 將字符串轉換爲int,int轉換爲字符串
- 15. 將字符串轉換爲「_」
- 16. 將字符串轉換爲
- 17. 將字符串轉換爲?
- 18. 將轉換器映射字符串轉換爲字符串
- 19. 將字符串轉換爲字符ascii
- 20. Java - 將字符串轉換爲字符[]
- 21. C++ - 將字符串轉換爲字符
- 22. 將字符*轉換爲字符串
- 23. 將字符串轉換爲字符
- 24. 將字符串轉換爲const *字符
- 25. 將字符[]轉換爲字符串
- 26. InfixToPostfix將字符轉換爲字符串
- 27. 將字符串轉換爲字符
- 28. 將char字符串轉換爲字符
- 29. 將字符串轉換爲字符
- 30. 將textField轉換爲字符串並將字符串轉換爲textField
考慮JodaTime代替 – harschware 2011-04-16 01:06:36
類似的問題:HTTP ://stackoverflow.c om/questions/4772425/format-date-in-java – Vadzim 2015-03-26 16:18:34