如何使用当前日期作为输入函数获取月份名称 [英] how to get month name using current date as input in function

查看:114
本文介绍了如何使用当前日期作为输入函数获取月份名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建一个获取当前日期和返回月份名称的功能?

我的日期不是当前日期,可以是2013/4/12或23/8 /的任何日期8。

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.

喜欢字符串monthName(2013/9/11);

当调用此函数返回月份名称时。

Like String monthName("2013/9/11");
when call this function return the month name.

推荐答案

这应该没问题。

这取决于日期的格式。
如果您尝试2011年2月1日
它会起作用,只需根据您的需要更改此字符串MMMM d,yyyy。
查看所有格式的模式。

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 this for all format patterns.

而且,月份是0,所以如果你想1月份是1,那么只需返回月份+ 1

And also, months are 0 based, so if you want January to be 1, just return month + 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;
}

正如我所说,检查我发布的所有格式模式的网页。如果您只想要月份的3个字符,请使用MMM而不是MMMM

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"

这篇关于如何使用当前日期作为输入函数获取月份名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆