[英]How can I parse a Date from a string and keep it in its format?
I have this code to convert a string to a date. 我有这段代码将字符串转换为日期。 but the resulting date is always in another format.
但结果日期始终采用其他格式。
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm");
try {
String dateString = "18/01/2013 11:59";
dateTest = format.parse(dateString);
System.out.println(dateTest); //output: Tue Jan 18 11:59:00 GMT 2013
}
How can I make it so that dateTest
is in the same format as the original? 如何使
dateTest
与原始格式相同?
使用与解析日期相同的SimpleDateFormat格式化日期。
This 这个
System.out.println(format.format(dateTest));
will do the job. 会做的工作。 You can use the
format()
method of your SimpleDateFormat
to format the output the same way your input should be. 您可以使用
SimpleDateFormat
的format()
方法以与输入相同的方式格式化输出。
You can't, because a Date does not have a 'format'. 您不能,因为日期没有“格式”。
If you need this, you could create your own Date class that contains a built-in format, but it'd be icky. 如果需要此功能,则可以创建自己的Date类,该类包含内置格式,但是会很麻烦。
The normal way is to format the date as you print it. 通常的方法是在打印日期时格式化日期。
System.out.println(format.format(dateTest));
Both java.util.Date and java.sql.Date store seconds and year, that's why you're seeing them when you print dateTest. java.util.Date和java.sql.Date都存储秒和年,这就是为什么在打印dateTest时会看到它们。 If you want print the date in the format you provided (dd/MM/yyyy HH:mm) you simply need to format the date.
如果要以提供的格式(dd / MM / yyyy HH:mm)打印日期,则只需格式化日期。
Date dateTest;
SimpleDateFormat desiredDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
try
{
String dateString = "18/01/2013 11:59";
dateTest = desiredDateFormat.parse(dateString);
System.out.println(desiredDateFormat.format(dateTest)); //output: 18/01/2013 11:59
}
catch (Exception ex)
{
//do something
}
输出时,请使用:
System.out.println(format.format(dateTest));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.