如何在java中将当前日期转换为字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2942857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert current date into string in java?
提问by user354299
How do I convert the current date into string in Java?
如何将当前日期转换为 Java 中的字符串?
回答by jasonmp85
// On the form: dow mon dd hh:mm:ss zzz yyyy
new Date().toString();
回答by Adamski
Use a DateFormatimplementation; e.g. SimpleDateFormat.
使用DateFormat实现;例如SimpleDateFormat。
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String data = df.format(new Date());
回答by Itay Karo
// GET DATE & TIME IN ANY FORMAT
import java.util.Calendar;
import java.text.SimpleDateFormat;
public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
public static String now() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
return sdf.format(cal.getTime());
}
Taken from here
取自这里
回答by Ian Purton
String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
回答by Johann Goulley
Faster :
快点 :
String date = FastDateFormat.getInstance("dd-MM-yyyy").format(System.currentTimeMillis( ));
回答by Basil Bourque
tl;dr
tl;博士
LocalDate.now()
.toString()
2017-01-23
2017-01-23
Better to specify the desired/expected time zone explicitly.
最好明确指定所需/预期的时区。
LocalDate.now( ZoneId.of( "America/Montreal" ) )
.toString()
java.time
时间
The modern way as of Java 8 and later is with the java.timeframework.
Java 8 及更高版本的现代方法是使用java.time框架。
Specify the time zone, as the date varies around the world at any given moment.
指定时区,因为日期在任何给定时刻在世界各地都不同。
ZoneId zoneId = ZoneId.of( "America/Montreal" ) ; // Or ZoneOffset.UTC or ZoneId.systemDefault()
LocalDate today = LocalDate.now( zoneId ) ;
String output = today.toString() ;
2017-01-23
2017-01-23
By default you get a String in standard ISO 8601format.
默认情况下,您会获得标准ISO 8601格式的字符串。
For other formats use the java.time.format.DateTimeFormatterclass.
对于其他格式,请使用java.time.format.DateTimeFormatter该类。
About java.time
关于java.time
The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
该java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat。
The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310。
You may exchange java.timeobjects directly with your database. Use a JDBC drivercompliant with JDBC 4.2or later. No need for strings, no need for java.sql.*classes.
您可以直接与您的数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC 驱动程序。不需要字符串,不需要类。java.sql.*
Where to obtain the java.time classes?
从哪里获得 java.time 类?
- Java SE 8, Java SE 9, Java SE 10, and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6and Java SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.time classes.
- For earlier Android (<26), the ThreeTenABPproject adapts ThreeTen-Backport(mentioned above). See How to use ThreeTenABP….
- Java SE 8、Java SE 9、Java SE 10及更高版本
- 内置。
- 具有捆绑实现的标准 Java API 的一部分。
- Java 9 添加了一些小功能和修复。
- Java SE 6和Java SE 7
- 多的java.time功能后移植到Java 6和7在ThreeTen-反向移植。
- 安卓
- 更高版本的 Android 捆绑实现 java.time 类。
- 对于早期的 Android(<26),ThreeTenABP项目采用了ThreeTen-Backport(上面提到过)。请参阅如何使用ThreeTenABP ...。
The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
该ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如Interval,YearWeek,YearQuarter,和更多。
回答by Swapnil Vargaonkar
Most of the answers are/were valid. The new JAVA API modification for Date handling made sure that some earlier ambiguity in java date handling is reduced.
大多数答案是/是有效的。用于日期处理的新 JAVA API 修改确保减少 Java 日期处理中的一些早期歧义。
You will get a deprecated message for similar calls.
对于类似的调用,您将收到一条已弃用的消息。
new Date() // deprecated
The above call had the developer to assume that a new Date object will give the Date object with current timestamp. This behavior is not consistent across other Java API classes.
上述调用让开发人员假设新的 Date 对象将提供具有当前时间戳的 Date 对象。此行为在其他 Java API 类中不一致。
The new way of doing this is using the CalendarInstance.
这样做的新方法是使用日历实例。
new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime()
Here too the naming convention is not perfect but this is much organised. For a person like me who has a hard time mugging up things but would never forget something if it sounds/appears logical, this is a good approach.
这里的命名约定也不是完美的,但这是有组织的。对于像我这样的人来说,如果事情听起来/看起来合乎逻辑,他们就很难忘记事情,但永远不会忘记,这是一个很好的方法。
This is more synonymous to real life
这更符合现实生活
- We get a Calendar object and we look for the time in it. ( you must be wondering no body gets time from a Calendar, that is why I said it is not perfect.But that is a different topic altogether)
- Then we want the date in a simple Text format so we use a SimpleDateFormat utility class which helps us in formatting the Date from Step 1. I have used yyyy, MM ,dd as parameters in the format. Supported date format parameters
- 我们得到一个 Calendar 对象,并在其中查找时间。(你一定想知道没有人从日历中获得时间,这就是为什么我说它并不完美。但这完全是一个不同的话题)
- 然后我们想要一个简单的文本格式的日期,所以我们使用一个 SimpleDateFormat 实用程序类,它帮助我们格式化步骤 1 中的日期。我使用 yyyy, MM ,dd 作为格式中的参数。支持的日期格式参数
One more way to do this is using Joda time API
另一种方法是使用 Joda 时间 API
new DateTime().toString("yyyy-MM-dd")
or the much obvious
或者很明显
new DateTime(Calendar.getInstance().getTime()).toString("yyyy-MM-dd")
both will return the same result.
两者都将返回相同的结果。
回答by Ganesh Reddy
public static Date getDateByString(String dateTime) {
if(dateTime==null || dateTime.isEmpty()) {
return null;
}
else{
String modified = dateTime + ".000+0000";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date dateObj = new Date();
Date dateObj1 = new Date();
try {
if (dateTime != null) {
dateObj = formatter.parse(modified);
}
} catch (ParseException e) {
e.printStackTrace();
}
return dateObj;
}
}
回答by Ganesh Reddy
For time as YYYY-MM-dd
时间为 YYYY-MM-dd
String time = new DateTime( yourData ).toString("yyyy-MM-dd");
And the Library of DateTime is:
而 DateTime 的库是:
import org.joda.time.DateTime;
导入 org.joda.time.DateTime;

