日期对象由日、月、年组成。

huangapple go评论68阅读模式
英文:

Date object from DAY, MONTH, YEAR

问题

以下是翻译好的内容:

我正在尝试创建一个方法,在Java中将DAY、MONTH和YEAR转换为Date对象。

我有以下代码:

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

我需要一个可配置的输出格式。

String format = "MM/dd/yyyy";

我将始终只获取"01"到"31"之间的DAY字符串,
始终只获取"1000"到"9999"之间的YEAR字符串,
始终只获取"01"到"12"之间的MONTH字符串(从不获取Jan、Feb等)。

我知道SimpleDateFormat(format)在一定程度上可以工作。

new SimpleDateFormat("MM/dd/yyyy")将解析"02/01/2010"为2010年2月1日
new SimpleDateFormat("mm/dd/yyyy")将解析"02/01/2010"为2010年1月1日

是否可能编写一个通用的Java方法,根据可配置的模式将给定的字符串(DAY、MONTH、YEAR)转换为Date对象?如果我提供错误的DAY、MONTH、YEAR组合(例如DAY = "31",MONTH = "02",YEAR = "2010"),是否可以抛出异常?

类似这样:

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

I am trying to create a method which converts DAY, MONTH, YEAR to Date object in Java

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
I will always get YEAR string from "1000" to "9999" only
I will always get MONTH string from "01" to "12" only (Never get Jan, Feb etc)

I understand that SimpleDateFormat(format) can work up to some extend.

new SimpleDateFormat("MM/dd/yyyy") will parse "02/01/2010" as Feb 01 2010 but
new SimpleDateFormat("mm/dd/yyyy") will parse "02/01/2010" as 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?? and which can throw exception is I supply a wrong combination of DAY, MONTH, YEAR (like DAY = "31", MONTH = "02", YEAR = "2010")

Something like :

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

答案1

得分: 2

有基本上有两种方法:

  1. 将每个字符串解析为数字,并将这些数字组合成日期。
  2. 将这些字符串组合成一个字符串,并将其解析为日期。

可能还有一些中间形式,但我建议您保持纯粹的立场,只使用其中一种方法。Arvind Kumar Avinash 的答案展示了选项1。我更偏向于选项2,让我来演示一下。

我建议您使用现代的 Java 日期和时间 API —— java.time 来处理日期。

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

由于11月只有30天,这段代码会合理地抛出一个异常:

Exception in thread "main" java.time.format.DateTimeParseException:
Text '2012-11-31' could not be parsed: Invalid date 'NOVEMBER 31'

也就是说,我们免费获得了输入验证。对于有效的日期,代码将解析日期并按要求进行格式化。

链接

Oracle 教程:日期时间 解释了如何使用 java.time。

英文:

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.

I recommend you use java.time, the modern Java date and time API for your date work.

	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:

> Exception in thread "main" java.time.format.DateTimeParseException:
> Text '2012-11-31' could not be parsed: Invalid date '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.

Oracle tutorial: Date Time explaining how to use java.time.

答案2

得分: 1

我建议您从过时且容易出错的java.util日期时间 API 和 SimpleDateFormat 切换到现代的java.time日期时间 API 以及相应的格式化 API(位于包java.time.format中)。从**教程:日期时间**中了解有关现代日期时间 API 的更多信息。

请注意,mm用于表示分钟,而不是。对于,应使用MM。详细信息请参阅此链接

使用现代日期时间 API:

import java.time.LocalDate;

public class Main {
    public static void main(String[] args) {
        // 测试
        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));
    }
}

输出:

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)

请注意,日期时间对象应该存储有关日期、时间、时区等信息,但不包括格式化信息。当打印日期时间类型的对象时,它会打印其toString方法返回的内容。如果您需要以不同的格式打印日期时间,您需要使用格式化类(例如DateTimeFormatter),该类可以以所需的模式返回字符串,例如:

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

public class Main {
    public static void main(String[] args) {
        // 测试
        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));
    }
}

输出:

Sunday 28 February 2010
2010 Feb Sun 28
英文:

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). Learn more about the modern date-time API from Trail: Date Time.

Note that mm is used for minute; not for month. For month, you use MM. Check this for more information.

Using the modern date-time 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. If you need to print the date-time in a different format, you need a formatting class (e.g. DateTimeFormatter) which can return you a string in your desired pattern e.g.

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

huangapple
  • 本文由 发表于 2020年9月30日 00:18:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/64123636.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定