![](/img/trans.png)
[英]NumberFormatException while parsing date with SimpleDateFormat.parse()
[英]simpledateformat parse not parsing date properly
我正在尝试将日期打印为:2013/11/20 08 30,但是在通过simpledateformat解析日期之后,它的打印方式如下:IST 2013年11月20日14:00:00星期三,这里我通过HH和MM作为08 30,但是解析后更改为14:00:00
你能建议一下吗
public class PrintDate {
public static void main(String[] args) {
System.out.println(getDate("2013/11/20","08","30"));
}
public static Date getDate(String date, String hour, String miniute) {
final SimpleDateFormat displayDateTimeFormat = new SimpleDateFormat("yyyy/MM/dd HH mm");
displayDateTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String paddedHour = hour.length() == 2 ? hour : "0" + hour;
int min = Integer.valueOf(miniute);
int remainder = min % 5;
int roundMinute = remainder > 2 ? min - remainder + 5 : min - remainder;
String minuteStr = String.valueOf(roundMinute);
String paddedMinuteStr = minuteStr.length() == 2 ? minuteStr : "0" + minuteStr;
String startDateStr = date + " " + paddedHour.toUpperCase() + " " + paddedMinuteStr;
Date startDate = null;
try {
startDate = displayDateTimeFormat.parse(startDateStr);
} catch (ParseException e) {
}
return startDate;
}
}
通过simpledateformat于2013年11月20日星期三14:00:00 IST解析日期后,在这里我通过了HH和MM作为08 30,但在解析后将其更改为14:00:00
是的,因为您指定要将其解析为UTC值。 但是,“ Date
本身没有时区的概念-只是时间的瞬间。 Date.toString()
将始终使用默认时区。
2013-11-20 08:30 UTC与IST 2013-11-20 14:00的时间相同,因此它实际上是在正确解析它-这只是Date.toString()
的结果,这使您感到困惑。
如果您还想保留时区,则必须单独进行操作-或(最好)使用Joda Time ,它是一种更好的日期/时间API,并具有DateTime
类,该类表示时间中的即时时间。特定的日历系统和时区。
只需尝试以下代码行即可获取所需格式的日期-
Date date=new Date(2013-1900,10,20,8,30);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyy/MM/dd K mm");
String strFormatDate = dateFormat.format(date);
Date dtFormatDate = dateFormat.parse(strFormatDate);
System.out.println("Formatted date in String:"+strFormatDate);
System.out.println("Formatted Date:"+dtFormatDate);
只需以K代替日期格式的HH即可。 您可以将日期设置为14 30,然后此格式也可以根据需要转换日期。
谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.