分享一个时间日期转换工具类DateTime
源码在最后面!!
注:时间日期表达格式(Android端基本都是这个格式)
字符 | 表达内容 |
---|---|
yyyy | 表示年份 |
MM | 表示月份 |
dd | 表示日 |
HH | 表示小时,24小时制 |
hh | 表示小时,12小时制 |
mm | 表示分钟 |
ss | 表示秒钟 |
还有一些不常见的属性,就不一一列举了。
一、生成对象DateTime的对象的三种方式
- 直接new,表示当前时间
DateTime dateTime=new DateTime()
- 传入一个毫秒值
DateTime dateTime=new DateTime(10000000);
- 解析日期时间,生成DateTime
DateTime dateTime = DateTime.parse("2016-10-12", "yyyy-mm-dd");
二、解析时间日期,生成字符串
- 生成默认格式字符串 结果为:2016-10-31 21:21:21
dateTime.toString();
- 生成特定格式的字符串 结果为:2016-10-31
dateTime.toString("yyyy-MM-dd");
三、小时运算(唯一的时间运算,有兴趣的朋友可以拓展)
//增加一小时
DateTime dateTime1 = dateTime.plusHour(1);
//减少一小时
DateTime dateTime2 = dateTime.plusHour(-1);
四、时间判断
- 两个dateTime对比,true 表示dateTime1在dateTime2之后
dateTime1.after(dateTime2);
- dateTime跟毫秒值对比
dateTime1.after(1000000);
五、其它一些获取参数的方法
- Date getDate() 获取当前时间的Date对象
- long getMillis() 获取当前时间的毫秒值
六、实际开发中的运用
- 格式转换:2016-10-21 21:22:23 转换成 2016-10-21
String timeStr = DateTime.parse("2016-10-21 21:22:23", "yyyy-MM-dd HH:mm:ss").toString("yyyy-MM-dd");
- 判断是否为当天
String todayStr = new DateTime().toString("yyyy-MM-dd");
if (todayStr.equals(dateTime.toString("yyyy-MM-dd"))) {
//true表示当天
}
特殊格式的时间JSON解析
{
"code": 0,
"message": "成功",
"data":{"nanos":0,"time":-27076233600000,"minutes":0,"seconds":0,"hours":0,"month":11,"timezoneOffset":-480,"year":-789,"day":5,"date":22}
}
遇到这种格式的日期时间,是不是有一种拿键盘砸后台的冲动。。不用慌,福利来了。
使用Gson解析 Entity为:
public class Entity {
private int code;
private String message;
private DateTime data;
}
介绍到此为止,基于最小内存原则,这个类写的非常简单,同时方便扩展。
package com.holly.common.help;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* @author Joey Huang(QQ:273179370)
* @created 2016/9/2
*/
public class DateTime {
private long time;
private Date mCurDate;
public DateTime() {
this(System.currentTimeMillis());
}
public DateTime(long currMillis) {
time = currMillis;
}
public String toString(String pattern) {
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
if (mCurDate == null) {
mCurDate = new Date(time);
} else {
mCurDate.setTime(time);
}
return dateFormat.format(mCurDate);
}
public String toString() {
return toString("yyyy-MM-dd HH:mm:ss");
}
public DateTime plusHour(int i) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(time);
calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) + i);
return new DateTime(calendar.getTimeInMillis());
}
public static DateTime parse(String timeStr, String pattern) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
try {
Date date = sdf.parse(timeStr);
return new DateTime(date.getTime());
} catch (ParseException e) {
return new DateTime();
}
}
public Date getDate() {
return new Date(time);
}
public long getMillis() {
return time;
}
public boolean after(DateTime dateTime) {
return time > dateTime.getMillis();
}
public boolean after(long millis) {
return this.time > millis;
}
}