Java的Date格式的应用

/**
 * 从秒数获得一个具体时间,24小时制,比如2016-12-12 23:23:15
 * @param second
 * @return
 */
public static String second2Moment24(long second){
    Date date = new Date(second*1000);
    SimpleDateFormat ft =
            new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    ft.setTimeZone(TimeZone.getTimeZone("GMT+8"));
    return ft.format(date);
}

/**
 * 从秒数获得一个具体时间,12小时制,比如2016-12-12 23:23:15
 * @param second
 * @return
 */
public static String second2Moment12(long second){
    Date date = new Date(second*1000);
    SimpleDateFormat ft =
            new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    ft.setTimeZone(TimeZone.getTimeZone("GMT+8"));
    return ft.format(date);
}

/**
 * 从秒数获得一个具体时间,24小时制,比如2016-12-12 23:23:15
 * @param second
 * @return
 */
public static String second2MomentGMT0(long second){
    Date date = new Date(second*1000);
    SimpleDateFormat ft =
            new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    ft.setTimeZone(TimeZone.getTimeZone("GMT+0"));
    return ft.format(date);
}

/**
 * 从一个具体时间,比如2016-12-12 23:23:15,获得秒数
 * @param time
 * @return
 */
public static long getTimeStamp(String time)
{
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));
    Date date = null;
    try
    {
        date = simpleDateFormat.parse(time);
    } catch (ParseException e)
    {
        return 0;
    }
    long timeStemp = date.getTime() / 1000;
    return timeStemp;
}

1、为什么从System.currentTimeMillis()转成标准时间格式会相差12个小时?
比如当前时间为2016-12-19 21:36:20,调用second2Moment12(System.currentTimeMillis()/1000),输出的是2016-12-19 09:36:20.
原因是弄混了12小时制和24小时制,SimpleDateFormat应该使用" yyyy-MM-dd HH:mm:ss"

2、为什么从System.currentTimeMillis()转成标准时间格式会相差8个小时?
比如当前时间为2016-12-19 21:36:20,调用second2MomentGMT0(System.currentTimeMillis()/1000),输出的是2016-12-19 13:36:20.
用System.currentTimeMillis()获取系统时间是国际标准的时间,是0时区的时间。原因有可能是SimpleDateFormat没有设置时区,ft.setTimeZone( TimeZone.getTimeZone("GMT+8"))。

3、如何从一个时间字符串比如2016-12-19 13:36:20获得其秒数,可以用来比较时间的早晚
比如当前时间为2016-12-19 21:36:20,调用getTimeStamp("2016-12-19 21:36:20"),输出的是1482154580.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值