Java 从整数创建 LocalDate 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29062204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create LocalDate Object from Integers
提问by Greg Valvo
If I already have a date's month, day, and year as integers, what's the best way to use them to create a LocalDate
object? I found this post String to LocalDate, but it starts with a String
representation of the date.
如果我已经将日期的月、日和年作为整数,那么使用它们创建LocalDate
对象的最佳方法是什么?我发现这篇文章String to LocalDate,但它以String
日期的表示开头。
采纳答案by Rohit Jain
Use LocalDate#of(int, int, int)
method that takes year, month and dayOfMonth.
使用LocalDate#of(int, int, int)
需要 year、month 和 dayOfMonth 的方法。
回答by Ugur Artun
In addition to Rohit's answer you can use this code to get Localdate from String
除了 Rohit 的答案,您还可以使用此代码从 String 获取 Localdate
String str = "2015-03-15";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate dateTime = LocalDate.parse(str, formatter);
System.out.println(dateTime);
回答by Dragos Rachieru
You can create LocalDate like this, using ints
您可以使用 ints 像这样创建 LocalDate
LocalDate inputDate = LocalDate.of(year,month,dayOfMonth);
and to create LocalDate from String you can use
并从您可以使用的字符串创建 LocalDate
String date = "04/04/2004";
inputDate = LocalDate.parse(date,
DateTimeFormat.forPattern("dd/MM/yyyy"));
You can use other formats too but you have to change String in forPattern(...)
您也可以使用其他格式,但您必须更改 forPattern(...) 中的 String