Convert String to Calendar Object in Java(在 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
这篇关于在 Java 中将字符串转换为日历对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Java 中将字符串转换为日历对象
基础教程推荐
- Struts2 URL 无法访问 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
