sweety
sweety

Reputation: 73

get date from timestamp

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.

Upvotes: 0

Views: 18226

Answers (3)

arajshree
arajshree

Reputation: 624

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

Upvotes: 2

JHS
JHS

Reputation: 7871

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);

Upvotes: 1

Steven You
Steven You

Reputation: 459

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");

Upvotes: 1

Related Questions