Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在';东部标准时间';时区_Java_Date_Calendar - Fatal编程技术网

Java 在';东部标准时间';时区

Java 在';东部标准时间';时区,java,date,calendar,Java,Date,Calendar,我必须将字符串解析为日期,比如说givenDate,解析为EST时区。 另外,我必须取当前日期,比如EST时区的currentDate。 我当前的时区是IST(格林尼治时间+5:30) 如果currentDate大于givenDate,则我需要在currentDate中添加一天 这是我已经实现的解决方案 SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy"); Calendar givenDate = Calendar.getInstan

我必须将字符串解析为日期,比如说
givenDate
,解析为EST时区。 另外,我必须取当前日期,比如EST时区的
currentDate
。 我当前的时区是IST(格林尼治时间+5:30)

如果currentDate大于givenDate,则我需要在currentDate中添加一天

这是我已经实现的解决方案

SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Calendar givenDate = Calendar.getInstance(TimeZone.getTimeZone("EST"));
givenDate .setTime(df.parse("01/08/2016"));

Calendar currentDate = Calendar.getInstance(TimeZone.getTimeZone("EST"));
if(currentDate.get(Calendar.YEAR) > givenDate .get(Calendar.YEAR) ||
            currentDate.get(Calendar.DAY_OF_YEAR) > givenDate.get(Calendar.DAY_OF_YEAR)){
        currentDate.add(Calendar.DATE, 1);
}

System.out.println("Final date : "+df.format(currentDate.getTime()));
有没有更好的解决办法

此外,以下几点一直在我的脑海中萦绕

考虑代码片段

SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");   
Calendar givenDate = Calendar.getInstance(TimeZone.getTimeZone("EST"));
givenDate .setTime(df.parse("01/07/2016"));
System.out.println(givenDate .get(Calendar.DATE));         //6       
System.out.println(givenDate .get(Calendar.DAY_OF_MONTH)); //6
System.out.println(givenDate .get(Calendar.DAY_OF_YEAR));  //6
为什么我的日期、月日、年日都是6分?我希望 他们必须返回7,因为给定的日期是从 2016年

但如果我在上述代码的第一行之后添加以下行,上述字段将返回7。这可能是什么原因

df.setTimeZone(TimeZone.getTimeZone("EST"));

.

您需要将时区设置到SimpleDataFormat类中,然后可以将解析的日期与当前时间进行比较:

SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
df.setTimeZone(TimeZone.getTimeZone("EST"));
Date givenDate = df.parse("01/08/2016");

Calendar currentDate = Calendar.getInstance();

if(currentDate.getTime().compareTo(givenDate) > 0) {
    currentTime.add(Calendar.DATE, 1);
}

请记住,Date对象表示UTC时区中的当前时间(自纪元起的秒数)。

请用涵盖所有可能情况的具体示例更新您的帖子,显示输入和预期输出。但我需要EST时区中的当前日期。date对象始终以UTC表示时间,无论您如何获得它。在您的示例中,甚至givenDate也使用UTC。时区仅在解析特定日期/时间或格式化日期/时间时生效。无论您的时区如何,当前时间(从新日期或日历对象开始)总是正确的。