Java开发中关于时间的转换(String & timestamp)

java 开发中经常需要对时间进行处理,最常见的就是String转timestamp和timestamp转String。

1.String 转Long(timestamp)

eg: String time="2019-05-22 08:30:45"

public long convertToTimestamp(String time) {

    if (null == time || time.equals("")) {
        return 0;
    }

    return Timestamp.valueOf(time).getTime();
}
  1. Long(timestamp) 转 String

public String convertToDate(long timestamp) {

    if (timestamp == 0) {
        return "";
    }
                //想要转换不同的格式,在SimpleDateFormat里面设置就好了
    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");

    Date date = new Date(timestamp);
    return sf.format(date);
}