Java 如何使用当前日期作为函数中的输入获取月份名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18806104/
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
how to get month name using current date as input in function
提问by user2762662
How do I create a function which take current date and return month name?
I have only date its not current date it can be any date like 2013/4/12 or 23/8/8.
如何创建一个获取当前日期并返回月份名称的函数?
我只有日期,它不是当前日期,它可以是任何日期,例如 2013/4/12 或 23/8/8。
Like String monthName("2013/9/11");
when call this function return the month name.
就像String monthName("2013/9/11");
调用此函数时返回月份名称一样。
采纳答案by Boy
This should be fine.
这应该没问题。
It depends on the format of date. If you try with February 1, 2011 it would work, just change this string "MMMM d, yyyy" according to your needs. Check thisfor all format patterns.
这取决于日期的格式。如果您尝试使用 2011 年 2 月 1 日它会工作,只需根据您的需要更改此字符串“MMMM d,yyyy”。检查这对所有格式模式。
And also, months are 0 based, so if you want January to be 1, just return month + 1
而且,月份是基于 0 的,所以如果您希望一月为 1,只需返回月份 + 1
private static int getMonth(String date) throws ParseException{
Date d = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(date);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
int month = cal.get(Calendar.MONTH);
return month + 1;
}
If you want month name try this
如果你想要月份名称试试这个
private static String getMonth(String date) throws ParseException{
Date d = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(date);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
String monthName = new SimpleDateFormat("MMMM").format(cal.getTime());
return monthName;
}
As I said, check web page I posted for all format patterns. If you want only 3 characters of month, use "MMM" instead of "MMMM"
正如我所说,检查我发布的所有格式模式的网页。如果您只想要月份的 3 个字符,请使用“MMM”而不是“MMMM”
回答by Vishal Pawale
Use this code -
使用此代码 -
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
int month = calendar.get(Calendar.MONTH);
So now you have month number, you can use switch case to get name for that month.
所以现在你有了月份号,你可以使用 switch case 来获取该月份的名称。
If your date is in string format use this-
如果您的日期是字符串格式,请使用此-
Date date = new SimpleDateFormat("yyyy-MM-dd").format(d)
回答by minomic
You can obtain the "number" of the month as described in the other answer and then you could simply use a switch to obtain a name. Example:
您可以获得其他答案中所述的月份的“数字”,然后您可以简单地使用开关来获取名称。例子:
switch(month) {
case 0:
your name is January
break;
...
}
P.S. I think months are zero-based but I'm not 100% sure...
PS 我认为月份是从零开始的,但我不是 100% 确定......