Simpledateformat 解析字符串日期错误

Simpledateformat parses string date wrong

我正在尝试将数据从字符串转换为 Data class,以便稍后将其与其他数据进行比较。

我的数据格式:dd-MM-yyyy(例如 31-07-2019)。

问题是在 format.parse("string date") 操作后显示错误的数据格式:

Wed Jul 31 00:00:00 UTC 2019

这是我的代码:

import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.*;

public class Program {

    public static void main(String[] args) {
        SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");

        try {
            String dateString = format.format(new Date());
            String dateStr = "31-07-2019";
            Date date = format.parse(dateStr);

            System.out.println(dateString);
            System.out.println(date);
        } catch (ParseException e) {
            System.out.println("ParseError " + e.getMessage());
        }       
    }
}

dateString(当前日期)解析成功。

我会说 SimpleDateFormat 是遗留的,使用 jdk-8 LocalDate

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate date1 = LocalDate.parse("31-07-2019",formatter);
LocalDate date2 = LocalDate.now();

你也可以用isBefore, isAfter来比较

date1.isAfter(date2);
date2.isBefore(date2);

默认 LocalDate returns ISO-8601 格式的日期

A date without a time-zone in the ISO-8601 calendar system, such as 2007-12-03.

比较后,您可以使用相同的格式化程序

LocalDate格式化为字符串
String date2 = LocalDate.now().format(formatter);

SimpleDateFormat.parse returns java.util.Date 对象

public Date parse(String source) throws ParseException

Date.toString()表示

的pattern字符串
public String toString()

 Converts this Date object to a String of the form:

     dow mon dd hh:mm:ss zzz yyyy

对日期和时间以及格式化和解析使用 java.time 而不是 java.util

public static void main(String args[]) throws Exception {
    // create a custom formatter for your pattern       
    DateTimeFormatter euroDtf = DateTimeFormatter.ofPattern("dd-MM-yyyy");
    // receive today's date
    LocalDate today = LocalDate.now();
    // parse a date that has the form of your pattern using your custom formatter
    LocalDate parsedDate = LocalDate.parse("31-07-2019", euroDtf);

    System.out.println("Today is " + today.format(euroDtf));
    System.out.println("Parsed date is " + parsedDate.format(euroDtf));
}

这是预期的行为

The class Date represents a specific instant in time, with millisecond precision.

format() 将在“format”中生成日期的字符串表示形式。 parse() 将 return 一个始终采用 "Fri Aug 02 16:14:21 SGT 2019" 格式的日期对象。

这里需要注意的是,构造函数中提供的模式应与使用 parse 方法解析的日期格式相同。