在 Java 中将字符串转换为日历对象
我是 Java 新手,通常使用 PHP.
I am new to Java, usually work with PHP.
我正在尝试转换这个字符串:
I am trying to convert this string:
2011 年 3 月 14 日星期一 16:02:37 GMT
Mon Mar 14 16:02:37 GMT 2011
到一个日历对象中,这样我就可以像这样轻松地提取年份和月份:
Into a Calendar Object so that I can easily pull the Year and Month like this:
String yearAndMonth = cal.get(Calendar.YEAR)+cal.get(Calendar.MONTH);
手动解析会是个坏主意吗?使用子字符串方法?
Would it be a bad idea to parse it manually? Using a substring method?
任何建议都会有所帮助,谢谢!
Any advice would help thanks!
推荐答案
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
cal.setTime(sdf.parse("Mon Mar 14 16:02:37 GMT 2011"));// all done
注意:根据您的环境/要求设置 Locale
note: set Locale
according to your environment/requirement
另见
- Javadoc
相关文章