在Android中以编程方式将GMT转换为IST时区

时间:2016-08-23 10:57:43

标签: java android

在我的应用程序中,我从服务器获取GMT格式的时间价值(YYYY-MM-DD hr-min-sec GMT),但我希望以IST格式显示(Aug-DD-YYYY hr-min-sec IST )。如何以编程方式进行?

1 个答案:

答案 0 :(得分:0)

我们将使用SimpleDateFormat类以特定格式格式化Date,我们将设置它的时区以在特定时区打印日期。

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class DateFormatter {

    /**
     * Utility function to convert java Date to TimeZone format
     * @param date
     * @param format
     * @param timeZone
     * @return
     */
    public static String formatDateToString(Date date, String format,
            String timeZone) {
        // null check
        if (date == null) return null;
        // create SimpleDateFormat object with input format
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        // default system timezone if passed null or empty
        if (timeZone == null || "".equalsIgnoreCase(timeZone.trim())) {
            timeZone = Calendar.getInstance().getTimeZone().getID();
        }
        // set timezone to SimpleDateFormat
        sdf.setTimeZone(TimeZone.getTimeZone(timeZone));
        // return Date in required format with timezone as String
        return sdf.format(date);
    }

    public static void main(String[] args) {
        //Test formatDateToString method
        Date date = new Date();
        System.out.println("Default Date:"+date.toString());
        System.out.println("System Date: "+formatDateToString(date, "dd MMM yyyy hh:mm:ss a", null));
        System.out.println("System Date in PST: "+formatDateToString(date, "dd MMM yyyy hh:mm:ss a", "PST"));
        System.out.println("System Date in IST: "+formatDateToString(date, "dd MMM yyyy hh:mm:ss a", "IST"));
        System.out.println("System Date in GMT: "+formatDateToString(date, "dd MMM yyyy hh:mm:ss a", "GMT"));
    }

}

以下是该计划的输出:

Default Date:Wed Nov 14 21:37:01 PST 2012
System Date: 14 Nov 2012 09:37:01 PM
System Date in PST: 14 Nov 2012 09:37:01 PM
System Date in IST: 15 Nov 2012 11:07:01 AM
System Date in GMT: 15 Nov 2012 05:37:01 AM