一、相关说明
跟日期和时间打交道时间很头疼的事情。这里就我目前遇到的一些情况和所查的资料做一个小结。
java中Date已经被Calendar和SimpleDateFormat两个类所取代,所以,如果遇到使用Date.getYear()等方法时总是出现黄色横线就表明这个方法已经弃用,不能编译通过。
这时候就应该改用Calendar类。
我之前的博客有关于String与日期时间、毫秒数之间的转换,点击这里。
这里就介绍一下两方面的内容,请注意红色部分。
String time="12-12-31 23:55:38";为例
二、获取年、月、日、时、分、秒
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
String time="12-12-31 23:55:38";
SimpleDateFormat format = new SimpleDateFormat("yy-MM-dd H:m:s");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date=format.parse(time);
cal.setTime(date);
int year=cal.get(Calendar.YEAR);
int month=cal.get(Calendar.MONTH);
int day=cal.get(Calendar.DAY_OF_MONTH);
int hour=cal.get(Calendar.HOUR_OF_DAY);
int minute=cal.get(Calendar.MINUTE);
int second=cal.get(Calendar.SECOND);
这里需要注意的是Calendar类默认使用的是美国时区,所以注意时区的问题。但是如果仅仅想提取出来毫秒,就无所谓时区的问题了。对于日期的问题,如果有不确定
的地方就应该多做实验,这是比较好的方法。
关于时间和日历的概念请参照这里。
另外,需要注意的是,Calendar的月是从0开始算的,如果想设置月份为8月,就应该给定值为7.
所以上面代码月份的输出应该是11.
同时,上面获取的月、日、时、分、秒都是当前时间的时分秒,而不是讲整个日期转转为时分秒所得出来的,即:上面所提取的时、分、秒分别是23、55、38.
三、更改年、月、日、时、分、秒
如果,我想仅仅对日期时间的某一个部分做修改,比如我只想将年份改为2014年,其余的月日、时、分、秒都不变,该如何处理呢。
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
String time="12-12-31 23:55:38";
SimpleDateFormat format = new SimpleDateFormat("yy-MM-dd H:m:s");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date=format.parse(time);
cal.setTime(date);
cal.set(Calendar.YEAR,2014);
只需要调用set(field,value)方法即可。类似更改月、日、时、分、秒都是类似的。