我有一个格式为 MM/dd/yyyy
的日期字符串,我正在使用 SimpleDateFormat
进行解析
现在假设下面给出的代码的 startDateString
是 11/26/2012
。我将时区设置为America/New_York
SimpleDateFormat df=new SimpleDateFormat("MM/dd/yyyy");
Date st = df.parse(startDateString);
Calendar startDate = Calendar.getInstance(TimeZone.getTimeZone("America/New_York"));
System.out.println("BEFORE : Start Date :"+startDate.getTime());
startDate.setTime(st);
System.out.println("AFTER : Start Date :"+startDate.getTime());
DateTimeZone timezone = DateTimeZone.forID("America/New_York");
DateTime actualStartDate = new DateTime(startDate,timezone);
System.out.println("JODA DATE TIME "+ actualStartDate);
上述代码片段的输出:
BEFORE : Start Date :Tue Nov 27 12:26:51 IST 2012
AFTER : Start Date :Mon Nov 26 00:00:00 IST 2012 //ok it sets date to 26th
//with all time parameters as 0.
JODA DATE TIME 2012-11-25T13:30:00.000-05:00 // here the date and
// time parameter are changed
当我像这样创建 actualStartDate
时,我的问题是:
DateTime actualStartDate = new DateTime(startDate,timezone);
日期更改为 25,时间更改为 13:00:00
我认为这是因为印度和美国之间的时区差异(距 IST 印度时间总计 -10:30)
我想要的是JODA DATE TIME 2012-11-26T00:00:00.000-05:00
我是否手动将 startDate
日历实例中的时间参数设置为 0
?
最佳答案
我怀疑问题是您在默认时区解析。这:
AFTER : Start Date :Mon Nov 26 00:00:00 IST 2012
显示您使用的时间是午夜 IST - 而不是纽约或 UTC 的午夜。目前 IST 为 UTC 18:30,因此您代表的时刻为 25-11-25T18:30:00Z。
当您将其转换为纽约时间时,您最终会得到 2012-11-25T13:30:00-05:00,这正是 Joda Time 正在做的事情。
我强烈建议:
- 您完全避免使用 Java 库(这就是所有问题的根源 - 无论是在解析方面,还是
Date.toString()
的结果都让您感到困惑) - 您使用
LocalDate
来表示日期,而不是DateTime
。毕竟,您试图表示一个日期,而不是一个瞬间。这完全绕过了时区,因为日期没有时区。
示例代码:
import java.util.*;
import org.joda.time.*;
import org.joda.time.format.*;
public class Test {
public static void main (String[] args) {
String text = "11/26/2012";
DateTimeFormatter formatter =
DateTimeFormat.forPattern("MM/dd/yyyy")
.withLocale(Locale.US);
LocalDate date = formatter.parseLocalDate(text);
System.out.println(date);
}
}
一旦您获得一个LocalDate
,如果您想找出特定时区当天开始的时刻,您可以使用 LocalDate.toDateTimeAtStartOfDay(DateTimeZone)
.
关于java - Joda Time 未得到预期结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13579114/