Android Date,时间字符串、时间戳等相互转换使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fengyeNom1/article/details/86014211

在软件开发中,我们会经常遇到各种时间的显示及判断,这就需要我们对获取的数据进行转换。

“yyyy-MM-dd HH:mm:ss” 这是常用的时间显示格式,表示了“年-月-日 时:分:秒”

注意:HH表示24小时制,hh表示12小时制

1、日期字符串转换Date实体

public static Date parseServerTime(String serverTime, String format) {
    if (format == null || format.isEmpty()) {
        format = "yyyy-MM-dd HH:mm:ss";
    }
    SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.CHINESE);
    sdf.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
    Date date = null;
    try {
        date = sdf.parse(serverTime);
    } catch (Exception e) {
        Timber.e(e, "");
    }
    return date;
}

参数一:时间字符串; 参数二:日期格式


2、秒数转换成时分秒

public static String convertSecToTimeString(long lSeconds) {
    long nHour = lSeconds / 3600;
    long nMin = lSeconds % 3600;
    long nSec = nMin % 60;
    nMin = nMin / 60;

    return String.format("%02d小时%02d分钟%02d秒", nHour, nMin, nSec);
}

3、Date对象获取时间字符串

public static String getDateStr(Date date,String format) {
    if (format == null || format.isEmpty()) {
        format = "yyyy-MM-dd HH:mm:ss";
    }
    SimpleDateFormat formatter = new SimpleDateFormat(format);
    return formatter.format(date);
}

猜你喜欢

转载自blog.csdn.net/fengyeNom1/article/details/86014211