代码之家  ›  专栏  ›  技术社区  ›  Amine Messaoudi

django的android格式日期时间

  •  3
  • Amine Messaoudi  · 技术社区  · 8 年前

    我正在使用JSON和REST框架将我的django网站连接到Android应用程序

    JSON数据包含如下日期时间:

    {
       date: "2018-06-05T12:42:48.545140Z"
    }
    

    当android收到日期时,我尝试使用以下代码对其进行格式化:

        String dt="2018-06-05T12:42:48.545140Z";
        DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm");
        String date=formatter.format(Date.parse(dt));
    

    我得到以下错误:

    java.lang.illegalargument异常:

    分析错误:2018-06-14T14:30:02.982009Z

    在Java.UTI.Deal.PARSEError(Dea.java:367)

    在Java.UTI.Deal.PalSE(Dea.java:448)

    在django模板中,我可以很容易地做到这一点

    物品.日期日期:'D-M-Y H:I'

    但在安卓系统里,我有点困惑

    2 回复  |  直到 8 年前
        1
  •  3
  •   Youcef LAIDANI    8 年前

    如果您正在使用 java.time 您可以使用的API:

    String dt = "2018-06-05T12:42:48.545140Z";
    ZonedDateTime zdt = ZonedDateTime.parse(dt); 
    String newFormat = zdt.format(DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm"));
    System.out.println(newFormat);//05/06/2018 12:42
    

    注意,我不使用任何格式设置工具 ZonedDateTime 无法分析您的日期。

    或作为 @Basil Bourque 提到它更适合解析为 Instance 而不是 分区日期时间 以下内容:

    String newFormat = Instant.parse(dt)
            .atZone(ZoneId.of("Pacific/Auckland"))
            .format(DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm"));
    

    关于你的错误

    你的错误来自 Date.parse(dt) 因为默认的日期模式不能解析您的日期,所以您需要给它正确的格式,以便它能够理解如何格式化您的日期。例如:

    String date = formatter.format(
            new SimpleDateFormat("the pattern which match your string date (dt)").format(dt)
    );
    

    但无论如何,我不建议使用 SimpleDateFormat Date .

    这个 ThreeTen-Backport 将端口返回到Java 6和AMP;7大部分 java.time 具有几乎相同的API语法的功能。进一步适应了早期的Android(<26) ThreeTenABP 项目。参见 How to use ThreeTenABP .

        2
  •  1
  •   Amine Messaoudi    8 年前

    我通过更改序列化程序类中的日期格式解决了这个问题。

        date = serializers.DateTimeField(format="%m/%d/%Y %H:%M", required=False, read_only=True)