从月份名称获取月份编号 [英] Get month number from month name

查看:121
本文介绍了从月份名称获取月份编号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个。

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String monthName = br.readLine();

如何获取monthName变量中包含的月份数?
谢谢!

How to get month number which contain in monthName variable? Thanks!

推荐答案

使用Java的日历类。它可以将任何给定的字符串解析为有效的日历实例。
这是一个例子(假设月份是英文)。

Use Java's Calendar class. It can parse any given string into a valid calendar instance. Here is an example (assuming that the month is in english).

Date date = new SimpleDateFormat("MMMM").parse(monthName);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
println(cal.get(Calendar.MONTH));

您可以在 SimpleDateFormat

String monthName = "März"; // German for march
Date date = new SimpleDateFormat("MMMM", Locale.GERMAN).parse(monthName);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
println(cal.get(Calendar.MONTH));

默认情况下,Java使用用户的本地来解析字符串。

By default, Java uses the user's local to parse the string.

请记住,计算机从0开始计数。因此,1月将为0.如果您想要人类可读日期,则应格式化日历实例:

Keep in mind that a computer starts counting at 0. So, January will be 0. If you want a human readable date, you should format the calendar instance:

SimpleDateFormat inputFormat = new SimpleDateFormat("MMMM");
Calendar cal = Calendar.getInstance();
cal.setTime(inputFormat.parse(monthName));
SimpleDateFormat outputFormat = new SimpleDateFormat("MM"); // 01-12
println(outputFormat.format(cal.getTime()));

这篇关于从月份名称获取月份编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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