get date from timestamp

旧街凉风 提交于 2019-12-25 04:45:51

问题


My code is:

import java.text.*;
import java.util.Date;

public class DateEx {
    public static void main(String[] args) {
        //String valueFromDB = "2012/06/06 00:00:00";

        String valueFromDB = "2012-12-31 00:00:00.0";
        Date d = new Date(valueFromDB);
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
        String dateWithoutTime = sdf.format(d);

        System.out.println("sdf.format(d) " + dateWithoutTime);

    }
}

It works for "2012/06/06 00:00:00" and I need to pass "2012-12-31 00:00:00.0" it is showing illegal argument. May be because I have use "-" in date or because of timestamp fraction second. I need date in dd-mm-yyyy format.


回答1:


Try this -

SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S");
String valueFromDB = "2012-12-31 00:00:00.0";
Date d1 = sdf1.parse(valueFromDB);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String dateWithoutTime = sdf.format(d1);
System.out.println("sdf.format(d) " + dateWithoutTime);



回答2:


This may be helpful.

long dateTimeStamp = 1487269800;
Timestamp stamp = new Timestamp(dateTimeStamp*1000);
Date changeDate = new Date(stamp.getTime());

Output:

Date :Fri Feb 17 00:00:00 IST 2017



回答3:


In order to parse a string to Date type, use the code below:

DateFormat formatter;
Date date;
formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
date = (Date)formatter.parse("2012-12-31 00:00:00");


来源:https://stackoverflow.com/questions/10749732/get-date-from-timestamp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!