按时区转换日历日期

时间:2018-04-11 06:48:13

标签: java date calendar timezone date-conversion

我将日期和时区作为字符串。我想按照给定的时区在日历对象中转换它们。为此,我写了下面的代码:

package com.test.practice;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.TimeZone;
public class PS1 {

    public static void main(String[] args) throws ParseException {

        String date1 = "2018-03-26T06:00:00Z";
        String timeZone = "GMT+02:00";
        Calendar cal1 = convertStringToDate(date1);
        Calendar cal2 = convertStringToDateWithTimeZone(date1,timeZone);
        System.out.println("cal1 is "+cal1.getTime());
        System.out.println("cal2 is "+cal2.getTime());

    }

    public static Calendar convertStringToDate(final String date) throws ParseException {
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
        final Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(date));
        return cal;
    }

       public static Calendar convertStringToDateWithTimeZone(final String date,String timezone) throws ParseException {
        final Calendar cal =  Calendar.getInstance();
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
        sdf.setTimeZone(TimeZone.getTimeZone(timezone));
        cal.setTime(sdf.parse(date));
        return cal;
    }

}

我正在尝试按时区打印日历对象而没有时区,但在这两种情况下我都得到相同的结果。 这是输出

cal1 is Mon Mar 26 11:30:00 IST 2018
cal2is Mon Mar 26 11:30:00 IST 2018

我在下面提到链接,但没有得到任何帮助。

Convert Date/Time for given Timezone - java https://www.journaldev.com/696/how-to-convert-java-date-into-specific-timezone-format Date and time conversion to some other Timezone in java

任何人都可以帮忙解决这个问题。

0 个答案:

没有答案