【问题标题】:How to convert String to TimeStamp [duplicate]如何将字符串转换为时间戳 [重复]
【发布时间】:2017-12-07 05:41:29
【问题描述】:

我想将字符串转换为时间戳。这是示例代码。

I want to parse the string to Timestamp..

我尝试将它转换为 字符串日期格式为“18/01/11”;

String date = "25/07/2017";
Timestamp ts =Timestamp.valueOf(date);
DateUtil.convertDate(ts.toString());

转换日期:-

SimpleDateFormat inputFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        Date d = null;
        try {
            d = inputFormat.parse(input);
        } catch (ParseException e) {
            System.out.println("Date Format Not Supported");
            e.printStackTrace();
        }
        SimpleDateFormat outputFormat = new SimpleDateFormat("dd/MM/yyyy");

        return outputFormat.format(d).toString();

如果我这样写,我会收到以下错误

Date Format Not Supported
Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]

【问题讨论】:

  • 你能写下实际的字符串吗?而且没有示例代码!
  • 您是否考虑过使用SimpleDateFormatString 解析为Date 值? 18/01/11yyyy-mm-dd 不一样
  • 答案在这里你可以检查它是否有效here
  • 请找到我的编辑.. 我添加了一些示例内容

标签: java date timestamp


【解决方案1】:

如果您的输入格式是dd/MM/yyyy,我认为您使用的格式正好相反:

//输入日期格式

SimpleDateFormat inputFormat = new SimpleDateFormat("dd/MM/yyyy");
Date d = null;
try {
    //convert string to date
    d = inputFormat.parse(input);
} catch (ParseException e) {
    System.out.println("Date Format Not Supported");
    e.printStackTrace();
}

//输出日期格式

SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

//将日期转换为时间戳

return  outputFormat.format(d).toString();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-27
    • 2019-10-29
    • 2013-10-21
    • 2012-05-16
    • 2012-02-15
    • 2017-01-18
    • 2020-11-22
    • 1970-01-01
    相关资源
    最近更新 更多