java 从日历中获取日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28013245/
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
Get date from calendar
提问by user2295277
Hi everyone in my program i receive a date like: 2015-01-18
大家好,我的程序中的每个人都收到了这样的日期:2015-01-18
It's a calendar object and i need to get the day, month and the year from the object. Right now i do something like:
这是一个日历对象,我需要从对象中获取日、月和年。现在我做这样的事情:
int day = date.get(Calendar.DAY_OF_MONTH);
int month = date.get(Calender.MONTH + 1);
int year = date.get(Calender.Year);
The output is:
输出是:
day = 18
month = 1
year = 2015
My problem is that i wanna get the month in this case like 01 and not 1 because that value is parsed later on my code and needs to be on that format. Is ugly to append the 0 before that 1 so anyone knoenter code herews a better way to do this? Thanks
我的问题是,我想在这种情况下获得月份,例如 01 而不是 1,因为该值稍后会在我的代码中解析并且需要采用该格式。在 1 之前附加 0 是丑陋的,所以任何人都知道输入代码是一种更好的方法来做到这一点吗?谢谢
回答by wassgren
If you need to pass the data as "01" an int
is the wrong datatype. You need to pass it as a String
. You can format the date using SimpleDateFormat
. That way you can choose which elements to pick from the date and the format they should have. Example:
如果您需要将数据作为“01”传递,则数据int
类型是错误的。您需要将其作为String
. 您可以使用 格式化日期SimpleDateFormat
。这样您就可以选择从日期中选择哪些元素以及它们应该具有的格式。例子:
final Calendar calendar = Calendar.getInstance();
final Date date = calendar.getTime();
String day = new SimpleDateFormat("dd").format(date); // always 2 digits
String month = new SimpleDateFormat("MM").format(date); // always 2 digits
String year = new SimpleDateFormat("yyyy").format(date); // 4 digit year
You can also format the full date like this:
您还可以像这样设置完整日期的格式:
String full = new SimpleDateFormat("yyyy-MM-dd").format(date); // e.g. 2015-01-18
The JavaDoc for SimpleDateFormatfully explains the various formatting options. Please note that SimpleDateFormat
is not thread safe.
SimpleDateFormat的JavaDoc充分解释了各种格式选项。请注意,这SimpleDateFormat
不是线程安全的。
回答by eckes
You need to
你需要
int month = cal.get(Calender.MONTH) + 1; // 0..11 -> 1..12
to get the int for the month (the + must be outside the argument).
获取该月的 int(+ 必须在参数之外)。
If you need a string with a leading zero from that integer, you can use textformat:
如果您需要该整数的前导零的字符串,您可以使用 textformat:
System.out.printf("month=%02d%n", month);
String monthStr = String.format("%02d", month);
But, you actually do not have to take the route via ints, you can directly format parts of a Date
into strings:
但是,您实际上不必通过 ints 走这条路线,您可以直接将 a 的一部分格式化Date
为字符串:
monthStr = new SimpleDateFormat("MM", Locale.ENGLISH).format(cal.getTime());