回答
在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. 转换DSTREAM [java.util.Date]到DSTREAM [字符串]
- 3. 如何将时间戳字符串转换为java.util.Date
- 4. 将字符串转换为字符串
- 5. 将java.sql.Date转换为java.util.Date
- 6. 将字符串转换为
- 7. 将字符串转换为“_”
- 8. 将字符串转换为?
- 9. 将字符串转换为字符
- 10. 将字符串转换为字符
- 11. 将字符串转换为字符
- 12. 将char字符串转换为字符
- 13. Java - 将字符串转换为字符[]
- 14. InfixToPostfix将字符转换为字符串
- 15. 将JavaScript符号转换为字符串?
- 16. 将字符串转换为运算符
- 17. JQuery.each将字符串文字转换为字符串。为什么?
- 18. 将字符串转换为数字node.js
- 19. Knockout.js将数字转换为字符串
- 20. 将字符串转换为字列表?
- 21. 将字符串转换为字节[]
- 22. Java - 将字节[]转换为字符串
- 23. 将字节转换为字符串
- 24. 将字符串转换为字节
- 25. 将字符串转换为数字
- 26. 将字符串转换为python字典
- 27. Python将字符串转换为字典
- 28. 将字节[]转换为UTF8字符串
- 29. 将字典转换为字符串
- 30. Android:EditTextPreference将字符串转换为数字
考虑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