Saturday 22 November 2014

Convert long value to yyyy-MM-dd HH:mm:ss.SSS format


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

public class DateConversion {
    static long getDateAsLong(String str) throws ParseException{
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        Date date = format.parse(str);
        return date.getTime();
    }

    static String getDateFromLong(long val){
        Date date1 = new Date(val);
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String dateFormatted = formatter.format(date1);
        return dateFormatted;
    }
    
    public static void main(String args[]) throws ParseException{
        String str = "2013-04-04 04:28:18.000";
        long time = getDateAsLong(str);
        System.out.println(time);

        String formattedDate = getDateFromLong(time);
        System.out.println(formattedDate);
    }
}


Output
1365029898000
2013-04-04 04:28:18.000

Previous                                                    Next                                                    Home

No comments:

Post a Comment