Needing help trying to Format DateTime

徘徊边缘 提交于 2021-01-29 20:11:48

问题


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.

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>

回答1:


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

What went wrong with your code:

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.

Using the modern date-time API:

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());

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.

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);
    }
}

Output:

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

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



来源:https://stackoverflow.com/questions/63195035/needing-help-trying-to-format-datetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!