【问题标题】:How to get local time Android如何获取本地时间Android
【发布时间】:2014-10-30 06:05:48
【问题描述】:

我的应用程序中有一个日期和时间字符串,例如:- 2014-10-30T11:30:00 我想将此字符串转换为我的本地时间,它应该看起来像这样 2014-10-30T11:30:00+05:30。我无法操作字符串,因为服务器端转换完成了时间的加法和减法。如何将 +05:30 偏移量添加到我的时间?

如何使用本地时间来让服务器知道我的语言环境?

【问题讨论】:

    标签: android datetime datetimeoffset


    【解决方案1】:

    试试这个方法,希望能帮助你解决问题。

    如何使用给定的功能:

    convertDateStringFormat("2014-10-30T11:30:00","yyyy-MM-dd'T'hh:mm:ss","yyyy-MM-dd'T'hh:mm:ss")

    这里你传递了三个参数:

    1.strDate    : which is represent datetime string.
    2.fromFormat : which is represent datetime format of your given datetime string.
    3.toFormat   : which is represent datetime format which you wan to convert your given  datetime string. 
    
    public String convertDateStringFormat(String strDate, String fromFormat, String toFormat){
       try{
           SimpleDateFormat sdf = new SimpleDateFormat(fromFormat);
           sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
           SimpleDateFormat dateFormat2 = new SimpleDateFormat(toFormat.trim());
           return dateFormat2.format(sdf.parse(strDate));
        }catch (Exception e) {
           e.printStackTrace();
           return "";
        }  
    }
    

    【讨论】:

    • 这将转换为 UTC 对吗?我想要本地转换
    • @iamstack,不,它将转换为本地,您给定的日期时间转换为 UTC,然后转换为本地。
    • 我尝试了您的代码,但出现异常 java.text.ParseException: Unparseable date: "2014-10-30 11:30:51" (at offset 10)
    • 那么你的 from 和 to 格式是“yyyy-MM-dd hh:mm:ss”。
    • convertDateStringFormat("2014-10-30 11:30:51","yyyy-MM-dd hh:mm:ss","yyyy-MM-dd hh:mm:ss")
    【解决方案2】:
      Calendar cal = Calendar.getInstance();
      TimeZone tz = cal.getTimeZone();
      SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
      sdf.setTimeZone(tz);
      long timestamp = cursor.getLong(columnIndex);
      Log.d("Server time: ", timestamp);
      String localTime = sdf.format(new Date(timestamp * 1000));
      Log.d("Time: ", localTime);
    

    【讨论】:

    • 这个怎么添加偏移量?
    • 您可以像这样添加偏移量 Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.getDefault());日期 currentLocalTime = calendar.getTime(); DateFormat date = new SimpleDateFormat("Z"); String localTime = date.format(currentLocalTime);
    猜你喜欢
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    • 2018-07-02
    • 2013-07-12
    • 2012-04-10
    相关资源
    最近更新 更多