java Data、String、Long三种日期类型之间的相互转换

以前做项目没遇到时间 、字符串、long型的三者之间的转化,最多也就两两转化,现在项目遇到了这么一个情况,感觉比较麻烦,但是呢再麻烦也得完成不,谁叫咱是苦逼的程序猿呢,经过百度加实践发现了他们之间互相转化的方法,这里列出来可供自己和大家以后直接使用。

// date类型转换为String类型
    // formatType格式为yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日 HH时mm分ss秒
    // data Date类型的时间
    public static String dateToString(Date data, String formatType) {
        return new SimpleDateFormat(formatType).format(data);
    }
 
    // long类型转换为String类型
    // currentTime要转换的long类型的时间
    // formatType要转换的string类型的时间格式
    public static String longToString(long currentTime, String formatType)
            throws ParseException {
        Date date = longToDate(currentTime, formatType); // long类型转成Date类型
        String strTime = dateToString(date, formatType); // date类型转成String
        return strTime;
    }
// string类型转换为date类型
    // strTime要转换的string类型的时间,formatType要转换的格式yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日
    // HH时mm分ss秒,
    // strTime的时间格式必须要与formatType的时间格式相同
    public static Date stringToDate(String strTime, String formatType)
            throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat(formatType);
        Date date = null;
        date = formatter.parse(strTime);
        return date;
    }
// long转换为Date类型
    // currentTime要转换的long类型的时间
    // formatType要转换的时间格式yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日 HH时mm分ss秒
    public static Date longToDate(long currentTime, String formatType)
            throws ParseException {
        Date dateOld = new Date(currentTime); // 根据long类型的毫秒数生命一个date类型的时间
        String sDateTime = dateToString(dateOld, formatType); // 把date类型的时间转换为string
        Date date = stringToDate(sDateTime, formatType); // 把String类型转换为Date类型
        return date;
    }
// string类型转换为long类型
    // strTime要转换的String类型的时间
    // formatType时间格式
    // strTime的时间格式和formatType的时间格式必须相同
    public static long stringToLong(String strTime, String formatType)
            throws ParseException {
        Date date = stringToDate(strTime, formatType); // String类型转成date类型
        if (date == null) {
            return 0;
        } else {
            long currentTime = dateToLong(date); // date类型转成long类型
            return currentTime;
        }
    }
// date类型转换为long类型
    // date要转换的date类型的时间
    public static long dateToLong(Date date) {
        return date.getTime();
}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 我爱你“氵” 雨已经下了两三天了,至今还没有停的意思,密密斜织的雨丝打在任何东西上都发出“沙沙”的声音,像白天鹅用...
    阿依嫫诗的月光阅读 384评论 0 1
  • 七月快结束了 七月初暑期社会实践,辗转多地,错过了一辆车,遇到了不少人。 七月中旬回到家乡,凌晨拖着行李箱出现在家...
    撰稿人留夏阅读 712评论 3 8
  • 这是二进制钢笔原创的第9篇文章。 初识认知 认知,第一次听到这个词是在《罗辑思维》节目中。 所谓认知,是指个体认识...
    二进制钢笔阅读 260评论 0 1

友情链接更多精彩内容