字符串中的Java Date对象无法正常工作 [英] Java Date object from String not working properly

查看:63
本文介绍了字符串中的Java Date对象无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个似乎无法解决的顽固问题。我在stackoverflow上寻找解决方案,并且发现了很多有关Java日期格式的文章,但是没有关于我所遇到的问题的具体信息。

I have run into a stubborn problem I cannot seem to solve. I have looked for solutions at stackoverflow and have found a lot of posts about Java date formatting, but nothing specific to the problem I have.

基本上,我遇到的情况是我需要将日期字符串转换为java.util.Date对象。我正在使用Date和SimpleDateFormat类。对于我遇到的大多数约会,它都可以正常工作。但是对于某些日期,它可以工作,但是会更改实际日期。日期的两个示例日期为:

Basically, I have a situation where I need to convert date strings into java.util.Date objects. I am using Date and SimpleDateFormat classes. For most dates that I am encountering, it works just fine. But for some dates, it works but changes the actual date. Two example dates that are :

2012年2月24日星期五PST->更改为-> 2012年1月6日星期五星期五15:45:40

Fri Feb 24 16:45:40 PST 2012 --> gets changed to --> Fri Jan 06 16:45:40 PST 2012

2012年6月13日星期三10:00:42->更改为-> 2012年1月4日星期三09:00:42 PST

Wed Jun 13 10:00:42 PDT 2012 --> gets changed to --> Wed Jan 04 09:00:42 PST 2012

有人知道为什么日期被更改了吗?有什么方法可以轻松避免这种情况,或者以其他方式做到这一点?我的代码复制如下。您可以尝试查看我在说什么。

Any idea why the dates are getting changed? Any way to easily avoid this or do it in a different way? My code is copied below. You can try it to see what I am talking about.

预先感谢!

您可以尝试一下并带有以下JSP代码:

You can try this with the following JSP code:

<%@ page import="java.util.*" %>
<%@ page import="java.net.*" %>
<%@ page import="java.io.*" %>
<%@ page import="java.text.*" %>

<%
String dateStr = "";
Date tmpDate = null;
DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z YYYY");

System.out.println("First Test ---------------");
dateStr = "Fri Feb 24 16:45:40 PST 2012";
tmpDate = (Date) formatter.parse(dateStr);
System.out.println("Original:"+dateStr+":");
System.out.println("Date Obj:"+tmpDate.toString()+":");

System.out.println("Second Test --------------");
dateStr = "Wed Jun 13 10:00:42 PDT 2012";
tmpDate = (Date) formatter.parse(dateStr);
System.out.println("Original:"+dateStr+":");
System.out.println("Date Obj:"+tmpDate.toString()+":");

%>

我得到以下输出:

First Test ------------
Original:Fri Feb 24 16:45:40 PST 2012:
Date Obj:Fri Jan 06 16:45:40 PST 2012:
Second Test -----------
Original:Wed Jun 13 10:00:42 PDT 2012:
Date Obj:Wed Jan 04 09:00:42 PST 2012:


推荐答案

在格式字符串中使用yyyy而不是YYYY。

Use yyyy not YYYY in your format string.

YYYY是非常特殊的事情,日历年。

YYYY is a very special thing, the calendar week year.

请参见 SimpleDateFormat 文档以获取更多信息。

See the SimpleDateFormat documentation for more info.

这篇关于字符串中的Java Date对象无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆