简体   繁体   English

来自 DAY、MONTH、YEAR 的日期对象

[英]Date object from DAY, MONTH, YEAR

I am trying to create a method which converts DAY, MONTH, YEAR to Date object in Java我正在尝试创建一个在 Java 中将 DAY、MONTH、YEAR 转换为 Date 对象的方法

I have我有

String DAY = "31"
String YEAR = "2012"
String MONTH = "11"

I need a configurable Format as output.我需要一个可配置的格式作为输出。

String format = "MM/dd/yyy";

I will always get DAY string from "01" to "31" only我将始终只获得从“01”到“31”的 DAY 字符串
I will always get YEAR string from "1000" to "9999" only我将始终只获得从“1000”到“9999”的 YEAR 字符串
I will always get MONTH string from "01" to "12" only (Never get Jan, Feb etc)我将始终只获得从“01”到“12”的 MONTH 字符串(永远不会得到 Jan、Feb 等)

I understand that SimpleDateFormat(format) can work up to some extend.我知道 SimpleDateFormat(format) 可以在一定程度上工作。

new SimpleDateFormat("MM/dd/yyyy") will parse "02/01/2010" as Feb 01 2010 but new SimpleDateFormat("MM/dd/yyyy") 会将 "02/01/2010" 解析为 2010 年 2 月 1 日,但
new SimpleDateFormat("mm/dd/yyyy") will parse "02/01/2010" as Jan 01 2010 new SimpleDateFormat("mm/dd/yyyy") 将解析 "02/01/2010" 为 Jan 01 2010

Is it possible to write a generic method in java which converts given Strings (DAY, MONTH, YEAR) to Date object based on a configurable pattern??是否可以在 java 中编写一个通用方法,根据可配置模式将给定的字符串(DAY、MONTH、YEAR)转换为 Date 对象? and which can throw exception is I supply a wrong combination of DAY, MONTH, YEAR (like DAY = "31", MONTH = "02", YEAR = "2010")并且可以抛出异常的是我提供了错误的 DAY、MONTH、YEAR 组合(例如 DAY = "31", MONTH = "02", YEAR = "2010")

Something like :就像是 :

Date dateParser(String format){
  
  String DAY = "01";
  String YEAR = "1922";
  String MONTH = "02";
  
  
  return date;
}

There are basically two ways:基本上有两种方式:

  1. Parse each string to a number and put the numbers together to a date.将每个字符串解析为一个数字,并将这些数字放在一起成为一个日期。
  2. Put the strings together to one string and parse it into a date.将字符串组合成一个字符串并将其解析为日期。

Some middle forms are thinkable, but I recommend you take a pure stance and use one of the ways only.一些中间形式是可以想象的,但我建议您采取纯粹的立场并仅使用其中一种方式。 The answer by Arvind Kumar Avinash shows option 1. My taste is rather for option 2., so let me demonstrate. Arvind Kumar Avinash 的答案显示了选项 1。我更喜欢选项 2.,所以让我演示一下。

I recommend you use java.time, the modern Java date and time API for your date work.我建议您使用 java.time,现代 Java 日期和时间 API 用于您的日期工作。

    String format = "MM/dd/yyy";
    
    String day = "31";
    String year = "2012";
    String month = "11";
    
    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(format, Locale.US);
    
    String isoDateString = year + '-' + month + '-' + day;
    LocalDate date = LocalDate.parse(isoDateString);
    
    String formattedDate = date.format(dateFormatter);
    System.out.println(formattedDate);

Since there are only 30 days in November (month 11), this code very sensibly throws an exception:由于 11 月(11 月)只有 30 天,这段代码非常明智地抛出了一个异常:

Exception in thread "main" java.time.format.DateTimeParseException: Text '2012-11-31' could not be parsed: Invalid date 'NOVEMBER 31'线程“main”中的异常 java.time.format.DateTimeParseException:无法解析文本“2012-11-31”:无效日期“NOVEMBER 31”

That is, we have got input validation for free.也就是说,我们有免费的输入验证。 For a valid date the code will parse the date and format as requested.对于有效日期,代码将根据要求解析日期和格式。

Link关联

Oracle tutorial: Date Time explaining how to use java.time. Oracle 教程:解释如何使用 java.time 的日期时间

I recommend you switch from the outdated and error-prone java.util date-time API and SimpleDateFormat to the modern java.time date-time API and the corresponding formatting API (package, java.time.format ).我建议您从过时且容易出错的java.util date-time API 和SimpleDateFormat切换到现代java.time date-time API 和相应的格式化 API(包, java.time.format )。 Learn more about the modern date-time API from Trail: Date Time .Trail: Date Time 中了解有关现代日期时间 API 的更多信息。

Note that mm is used for minute ;请注意, mm用于表示minute not for month .不是month For month , you use MM .对于month ,你用MM Check this for more information.检查这个以获取更多信息。

Using the modern date-time API:使用现代日期时间 API:

import java.time.LocalDate;

public class Main {
    public static void main(String[] args) {
        // Test
        System.out.println(getLocalDate("2010", "02", "28"));
        System.out.println(getLocalDate("2010", "02", "31"));
    }

    static LocalDate getLocalDate(String year, String month, String dayOfMonth) {
        return LocalDate.of(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(dayOfMonth));
    }
}

Output:输出:

2010-02-28
Exception in thread "main" java.time.DateTimeException: Invalid date 'FEBRUARY 31'
    at java.base/java.time.LocalDate.create(LocalDate.java:459)
    at java.base/java.time.LocalDate.of(LocalDate.java:271)
    at Main.getLocalDate(Main.java:11)
    at Main.main(Main.java:7)

Note that a date-time object is supposed to store the information about date, time, time-zone etc. but not about the formatting.请注意,日期时间对象应该存储有关日期、时间、时区等的信息,而不是有关格式的信息。 When you print an object of a date-time type, its is supposed to print what its toString method returns.当您打印日期时间类型的对象时,它应该打印其toString方法返回的内容。 If you need to print the date-time in a different format, you need a formatting class (eg DateTimeFormatter ) which can return you a string in your desired pattern eg如果您需要以不同的格式打印日期时间,您需要一个格式化类(例如DateTimeFormatter ),它可以以您想要的模式返回一个字符串,例如

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        // Test
        System.out.println(getFormattedLocalDate("2010/02/28", "yyyy/MM/dd", "EEEE dd MMMM yyyy"));
        System.out.println(getFormattedLocalDate("28/02/2010", "dd/MM/yyyy", "yyyy MMM EEE dd"));
    }

    static String getFormattedLocalDate(String date, String inputPattern, String outputPattern) {
        return LocalDate.parse(date, DateTimeFormatter.ofPattern(inputPattern))
                .format(DateTimeFormatter.ofPattern(outputPattern));
    }
}

Output:输出:

Sunday 28 February 2010
2010 Feb Sun 28

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM