zoukankan      html  css  js  c++  java
  • data和string类型之间的相互转换

    package main;

    import java.text.SimpleDateFormat;
    import java.util.Date;

    import freemarker.core.ParseException;

    public class Transformation {
    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;
    try {
    date = formatter.parse(strTime);
    } catch (java.text.ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    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 stringToLong2(String strTime, String formatType) throws ParseException{
    return stringToLong(strTime,formatType)-stringToLong("1970-01-01",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();
    }

    }

  • 相关阅读:
    微信公众号开发的经验与坑
    微信公众号开发经验总结
    微信H5中禁止分享好友及分享到朋友圈的方法
    js 实现纯前端将数据导出excel两种方式,亲测有效
    JavaScript数组的一些方法、数学对象、定时器
    几种动态轨迹可视化效果实现方案-echarts、mapv、deck.gl
    前端大牛的博客收集
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
  • 原文地址:https://www.cnblogs.com/changhuiming/p/11024459.html
Copyright © 2011-2022 走看看