【问题标题】:Convert GMT to IST time zone programmatically in Android [duplicate]在Android中以编程方式将GMT转换为IST时区[重复]
【发布时间】:2016-12-30 04:05:10
【问题描述】:

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

【问题讨论】:

  • 发帖前请先搜索 Stack Overflow。

标签: java android


【解决方案1】:

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

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

【讨论】:

  • 我正在从服务器获取 GMT 格式的字符串值,例如(yyyy-mm-dd hh:mm:ss GMT)..我不知道应用上述类来获取 IST 格式。 .请用简单的代码帮我..
  • 请显示字符串值
  • 字符串值为 2016-01-18 09:27:01
  • @BaskarP 你有解决方案吗?
猜你喜欢
  • 1970-01-01
  • 2012-12-25
  • 1970-01-01
  • 2018-08-16
  • 1970-01-01
  • 2014-06-07
  • 2012-10-24
  • 2021-06-01
  • 2021-08-15
相关资源
最近更新 更多