java 从时间戳获取日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10749732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 02:22:34  来源:igfitidea点击:

get date from timestamp

javadate-formatsimpledateformat

提问by sweety

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-yyyyformat.

它适用于"2012/06/06 00:00:00"我需要通过"2012-12-31 00:00:00.0"它显示非法参数。可能是因为我使用"-"了日期或因为时间戳分数秒。我需要dd-mm-yyyy格式的日期。

回答by arajshree

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

回答by Steven You

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

要将字符串解析为 Date 类型,请使用以下代码:

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

回答by JHS

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