Category: Java Basic Knowledge

Conversion between Timestamp and date, Java-based.

Sometimes, we need to do some conversions between timestamp and date. Here are my solutions.

1. Converting date to timestamp


1
2
3
4
5
6
public static long dateToStamp(String s) throws ParseException{
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse(s);
        long ts = date.getTime();
        return ts;
}

2.Converting timestamp to date


1
2
3
4
5
6
7
public static String stampToDate(long s){
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(s);
        res = simpleDateFormat.format(date);
        return res;
}

 

Don’t forget to import  java.util.Date and  java.text.SimpleDateFormat.