首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将日期更改为设备本地时区上的字符串

将日期更改为设备本地时区上的字符串
EN

Stack Overflow用户
提问于 2020-09-15 15:31:50
回答 3查看 58关注 0票数 2

我正在从数据库中获取一个Date数据类型,就像这样Mon Sep 14 11:30:00 GMT+03:00 2020.I想要将这个值更改为一个字符串,所以我使用了这个函数。

代码语言:javascript
运行
复制
public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm";


public static String dateToString(Date date){
    DateFormat dateFormat = new SimpleDateFormat(General.DATE_FORMAT);
    dateFormat.setTimeZone(TimeZone.getDefault());
    if(date == null)
        return "";
    return dateFormat.format(date);
}

这个函数给了我这个输出2020-09-14 11:30,但是根据我的安卓设备时区,它应该是2020-09-14 02:30。有什么建议吗?

EN

回答 3

Stack Overflow用户

发布于 2020-09-15 16:15:29

你可以使用来做这件事,现在可以通过Android API Desugaring降低Android API的级别。

代码语言:javascript
运行
复制
public static void main(String[] args) {
    // (nearly) your example pattern for output (u is better here)
    final String DATE_FORMAT = "uuuu-MM-dd HH:mm";
    // use it to create an output formatter
    DateTimeFormatter outputDtf = DateTimeFormatter.ofPattern(DATE_FORMAT);
    // your example String
    String exampleDate = "Mon Sep 14 11:30:00 GMT+03:00 2020";
    // parse it with a suitable formatter using a specific pattern and a Locale for names
    DateTimeFormatter parserDtf = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss O uuuu",
                                                                Locale.ENGLISH);
    // then parse the example String
    OffsetDateTime odt = OffsetDateTime.parse(exampleDate, parserDtf);
    // get your local offset (the one of your device)
    ZoneOffset localOffset = OffsetDateTime.now().getOffset();
    // and adjust the offset to your local one
    OffsetDateTime localOdt = odt.withOffsetSameInstant(localOffset);
    // and output it (on android, use log...)
    System.out.println(odt.format(outputDtf));  // example datetime
    System.out.println(localOdt.format(outputDtf)); // same time in local offset
}

此代码输出

代码语言:javascript
运行
复制
2020-09-14 11:30
2020-09-14 10:30

请注意,输出--当然--是我当前的偏移量,也就是UTC+02:00。

票数 1
EN

Stack Overflow用户

发布于 2020-09-15 16:25:53

试用LocalegetDefault()方法

代码语言:javascript
运行
复制
public static String dateToString(Date date){
    DateFormat dateFormat = new SimpleDateFormat(General.DATE_FORMAT, Locale.getDefault());
    dateFormat.setTimeZone(TimeZone.getDefault());
    if(date == null)
        return "";
    return dateFormat.format(date);
}

希望它能为你工作。谢谢。

票数 1
EN

Stack Overflow用户

发布于 2020-09-15 15:46:19

尝试在此之前设置

代码语言:javascript
运行
复制
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63897101

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档