常用时间处理方法:时间戳和格式化时间之间转换;时间比大小
2016-04-08 17:11
375 查看
1、获取当前格式化时间:
2、两个时间比大小(工具类形式给出)
注:注意参数格式,要和方法里的SimpleDateFormat指定的格式一致
3、格式化时间转成时间戳
4、时间戳转成格式化时间
验证3、4方法时,将3的格式化时间变成时间戳,然后把得到的时间戳用4变成格式化时间,对比可知
方法3、4的结果
// 获取当前时间的时间戳,并转换成格式化时间 long getNowTimeLong = System.currentTimeMillis(); //转换成12小时进制 SimpleDateFormat fromatTime_12 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); String time_12 = fromatTime_12.format(getNowTimeLong); System.out.println("time_12---"+time_12); //转换成24小时进制 SimpleDateFormat fromatTime_24 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time_24 = fromatTime_24.format(getNowTimeLong); System.out.println("time_24---"+time_24);
2、两个时间比大小(工具类形式给出)
public static int compare_date(String DATE1, String DATE2) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm"); try { Date dt1 = df.parse(DATE1); Date dt2 = df.parse(DATE2); if (dt1.getTime() > dt2.getTime()) { return 1; } else if (dt1.getTime() < dt2.getTime()) { return -1; } else { return 0; } } catch (Exception exception) { exception.printStackTrace(); } return -2; }
注:注意参数格式,要和方法里的SimpleDateFormat指定的格式一致
3、格式化时间转成时间戳
// 格式化时间,转换成long类型 Date date = null; String dateString = "2016-04-08 16:30:50"; SimpleDateFormat formatTiem2long = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { date = formatTiem2long.parse(dateString); } catch (ParseException e) { e.printStackTrace(); } long longFormatTime = date.getTime(); // 有时候,自己电脑或者手机上的时间,会和服务器差8个小时,这个时候,就用下面注释的这句。看情况而定 // long longFormatTime = date.getTime() - 28800000; System.out.println("longFormatTime--" + longFormatTime);
4、时间戳转成格式化时间
// long类型的时间戳,转换成格式化时间 SimpleDateFormat long2FormatTime = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒"); String re_StrTime = long2FormatTime.format(new Date(longFormatTime)); System.out.println("re_StrTime--" + re_StrTime);
验证3、4方法时,将3的格式化时间变成时间戳,然后把得到的时间戳用4变成格式化时间,对比可知
方法3、4的结果
longFormatTime--1460104250000 re_StrTime--2016年04月08日16时30分50秒
相关文章推荐
- git常用命令介绍
- 随机序列生成算法---生成前N个整数的一组随机序列
- openssl 非对称加密算法DSA命令详解
- java使用部分字符串搜索文件
- LeetCode 238 -Product of Array Except Self ( JAVA )
- POJ2777_Count Color
- PHP用redis实现多进程队列
- [IOS 开发] GCD常用方法
- Objective-C简单的音乐播放器(边下边播)
- shader内置变量和函数
- zcat,zgrep用法
- 无向图的双连通性
- dede让channelartlist标签支持currentstyle属性 完美解决
- SpringMVC Controller介绍
- 纸牌博弈
- flask框架配置email问题汇总,包括163邮箱,qq邮箱,gmail等国内外邮箱
- C#-类的应用
- 升级java1.8及ssh版本中碰到的问题(四)
- 结构体对齐
- JSON需要的jar包和和String类型转JSON