Android 时间日期与时间戳相互转化,其特殊时间格式的转化?

一、正常日期与时间的转化

/*
 * 将时间戳转换为时间
 *
 * s就是时间戳
 */

public static String stampToDate(String s) {
    String res;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    //如果它本来就是long类型的,则不用写这一步
    long lt = new Long(s);
    Date date = new Date(lt);
    res = simpleDateFormat.format(date);
    return res;
}

/*
 * 将时间戳转换为时间
 *
 * s就是时间戳
 */

public static String stampToDateS(String s, String fprmat) {
    String res;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(fprmat);
    //如果它本来就是long类型的,则不用写这一步
    long lt = new Long(s);
    Date date = new Date(lt);
    res = simpleDateFormat.format(date);
    return res;
}

/*
 * 将时间转换为时间戳
 */
@SuppressLint("SimpleDateFormat")
public static String dateToStamp(String s) throws ParseException {
    String res;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = simpleDateFormat.parse(s);
    long ts = date.getTime();
    res = String.valueOf(ts);
    return res;
}

二、接收到后台传来的时间格式2019-04-30T15:59:59.000+0000,如何转换

/**
 * 将 2018-08-21T03:12:58.000+0000 格式化为日期
 */
public static String dealDateFormat(String oldDate) {
    Date date1 = null;
    DateFormat df2 = null;
    try {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        Date date = df.parse(oldDate);
        SimpleDateFormat df1 = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.UK);
        date1 = df1.parse(date.toString());
        df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return df2.format(date1);
}

因为在很多地方都引用,请牢记!!!

 

最后是交流公众号,大家可以关注一下


版权声明:本文为yyxhzdm原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。