需要帮助尝试格式化DateTime [英] Needing help trying to Format DateTime

查看:85
本文介绍了需要帮助尝试格式化DateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,对于我的分配,我被指示为Shopify集成创建单元测试.我的assert方法之一要求我以某种方式设置日期格式.

So for my assignemtn,I am instructed to create unit tests for Shopify integration. One of my assert methods require me to format the date a certain way.

我的assert方法是这个,下面的跟踪如下.要跟上文档的步伐真的很困难.

My assert method is this and the following trace is as follows. It's really difficult trying to keep up with the documentations.

assertEquals((new Date(2020, 7, 23)),order.getCreatedAt());

java.lang.AssertionError: expected:<Mon Aug 23 00:00:00 EDT 3920> but was:<2020-07-23T11:47:45.000-04:00>

推荐答案

我建议您从过时且容易出错的java.util.Date切换到

I suggest you switch from the outdated and error-prone java.util.Date to the modern date-time API.

java.util.Date将第一个月视为0,这意味着7代表August.另外,它将1900添加到参数year中,这意味着对于2020作为此参数的值,它将为您提供一个年份设置为3920的对象.我希望,这足以了解java.util.Date的设计多么可怕.

java.util.Date considers the first month as 0 which means 7 stands for August with it. Also, it adds 1900 to the parameter, year which means that for 2020 as the value of this parameter, it will give you an object with the year set as 3920. I hope, this is enough to understand how horribly java.util.Date has been designed.

您可以按照以下步骤进行操作:

You can do it as follows:

OffsetDateTime testData = OffsetDateTime.of(LocalDateTime.of(2020, Month.JULY, 23, 11, 47, 45, 0),
                ZoneOffset.ofHours(-4));
assertEquals(testData, order.getCreatedAt());

这基于order.getCreatedAt()返回OffsetDateTime对象的假设.请注意,您可以使用7代替Month.JULY,但是后者是表示月份值的惯用方式.

This is based on the assumption that order.getCreatedAt() returns an object of OffsetDateTime. Note that you can use, 7 instead of Month.JULY but the later is the idiomatic way of expressing the value of the month.

如果order.getCreatedAt()返回2020-07-23T11:47:45.000-04:00作为String,则可以将其解析为OffsetDateTime,如下所示:

If order.getCreatedAt() returns 2020-07-23T11:47:45.000-04:00 as String, you can parse it to OffsetDateTime as shown below:

import java.time.LocalDateTime;
import java.time.Month;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;

public class Main {
    public static void main(String[] args) {
        // Parse the given date-time string to OffsetDateTime
        OffsetDateTime orderCreatedAt = OffsetDateTime.parse("2020-07-23T11:47:45.000-04:00");

        // Create test data
        OffsetDateTime testData = OffsetDateTime.of(LocalDateTime.of(2020, Month.JULY, 23, 11, 47, 45, 0),
                ZoneOffset.ofHours(-4));

        // Display
        System.out.println(orderCreatedAt);
        System.out.println(testData);

        // Assert
        //assertEquals(testData, orderCreatedAt);
    }
}

输出:

2020-07-23T11:47:45-04:00
2020-07-23T11:47:45-04:00

通过 Trail:Date了解有关现代日期时间API的更多信息时间 .

Learn more about modern date-time API from Trail: Date Time.

这篇关于需要帮助尝试格式化DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆