嗨,我想将当前日期转换为这种格式 YYYY-MM-DD
。但是,它会将日期转换为 String
格式,而我希望将其转换回 Date
格式。所以有人能给个建议吗?
这是我目前的代码:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String datestring = dateFormat.format(date);
嗨,我想将当前日期转换为这种格式 YYYY-MM-DD
。但是,它会将日期转换为 String
格式,而我希望将其转换回 Date
格式。所以有人能给个建议吗?
这是我目前的代码:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String datestring = dateFormat.format(date);
试试这个:
String DATE_FORMAT_NOW = "yyyy-MM-dd";
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
String stringDate = sdf.format(date );
try {
Date date2 = sdf.parse(stringDate);
} catch(ParseException e){
//Exception handling
} catch(Exception e){
//handle exception
}
DateFormat#parse(String)
方法:Date date = dateFormat.parse("2013-10-22");
datestring
。直接使用它替代 qqilihq 的示例中的常量。 - Dawood ibn Kareem如何将日期转换为字符串并再次转换为日期?
LocalDate.now().toString()
LocalDate.parse( "2017-01-23" )
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate ld = LocalDate.now( z ) ;
您期望的YYYY-MM-DD格式恰好符合ISO 8601标准。
当解析/生成字符串时,java.time类默认使用该标准。因此,您可以直接调用LocalDate::parse
和LocalDate::toString
而无需指定格式化模式。
String s = ld.toString() ;
进行解析:
LocalDate ld = LocalDate.parse( s ) ;
java.time框架已经内置于Java 8及其之后的版本中。这些类取代了繁琐的旧式遗留日期时间类,如java.util.Date
、Calendar
和SimpleDateFormat
。
Joda-Time项目现在处于维护模式,建议迁移到java.time类。
要了解更多信息,请查看Oracle教程。并在Stack Overflow上搜索许多示例和解释。规范是JSR 310。ThreeTen-Extra项目通过添加额外的类扩展了java.time。该项目是java.time可能未来增加内容的试验场。您可能会在这里找到一些有用的类,如Interval
, YearWeek
, YearQuarter
和更多。
TimeZone.setDefault
可以在 JVM 运行时被任何线程的任何应用程序中的任何代码调用。更改会立即影响该 JVM 中所有其他线程运行的所有其他代码。这是相当不可预测的,超出了程序员的控制范围。通过传递可选的 ZoneId
参数始终明确指定所需/期望的时区。 - Basil Bourquepublic String convertDateToString(Date date, String format) {
String dateStr = null;
DateFormat df = new SimpleDateFormat(format);
try {
dateStr = df.format(date);
} catch (Exception ex) {
System.out.println(ex);
}
return dateStr;
}
从Java中将日期转换为字符串。然后再将字符串转换为日期
public Date convertStringToDate(String dateStr, String format) {
Date date = null;
DateFormat df = new SimpleDateFormat(format);
try {
date = df.parse(dateStr);
} catch (Exception ex) {
System.out.println(ex);
}
return date;
}
尝试使用此函数
public static Date StringToDate(String strDate) throws ModuleException {
Date dtReturn = null;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd");
try {
dtReturn = simpleDateFormat.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
return dtReturn;
}