如何将字符串日期转换为 Java 中的时间戳,格式为 dd-MMM-yyyy?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18777770/
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-08-12 10:57:20  来源:igfitidea点击:

How to convert string Date to Timestamp in Java for the format dd-MMM-yyyy?

javasql

提问by Java Developer

I want to convert string Date to Timestamp in java. The following are the codes that I have written. The date value passed is in the format 19-SEP-2013.

我想在java中将字符串日期转换为时间戳。以下是我编写的代码。传递的日期值的格式为19-SEP-2013

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
Date date = dateFormat.parse(tcmo.getCtsDate());
ps.setTimestamp(ctr++, new Timestamp(date.getTime());

The variable ctris declared already. psis the PreparedStatementobject. Later codes include ps.executeUpdate().

变量ctr已经声明。psPreparedStatement对象。后来的代码包括ps.executeUpdate().

tcmo.getCtsDate()returns the value 19-Sep-2013.

tcmo.getCtsDate()返回值 19-Sep-2013。

Database can accept only Timestamp in the format 2013-09-19 00:00:00.0

数据库只能接受格式为2013-09-19 00:00:00.0 的时间戳

The exception thrown is Unparseable Date "19-SEP-2013". can anyone help me to clear this?

抛出的异常是Unparseable Date "19-SEP-2013". 谁能帮我清除这个?

回答by MadProgrammer

Your format String(yyyy-mm-dd HH:mm:ss) and your input (19-SEP-2013) don't match.

您的格式String( yyyy-mm-dd HH:mm:ss) 和您的输入 ( 19-SEP-2013) 不匹配。

A format of dd-MMM-yyyywould be required to parse the Stringto a Dateobject

dd-MMM-yyyy将需要的格式解析StringDate对象

For example...

例如...

try {
    String text = "19-SEP-2013";
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
    Date date = sdf.parse(text);
    System.out.println(text + " to " + date);
} catch (ParseException exp) {
    exp.printStackTrace();
}

Outputs...

输出...

19-SEP-2013 to Thu Sep 19 00:00:00 EST 2013

回答by lealand

Try replacing the first line with

尝试将第一行替换为

SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");

This should resolve the parsing error.

这应该可以解决解析错误。

Further information about SimpleDateFormat, including what are valid letters, can be found in the Oracle JavaDocs.

有关 SimpleDateFormat 的更多信息,包括什么是有效字母,可以在 Oracle JavaDocs 中找到

回答by Bohemian

This is a "gotcha" that traps many programmers new to java. The format character mis for minutesand Mis for months..

这是一个“陷阱”,它使许多 Java 新手陷入困境。格式字符m分钟M..

Your format string of "yyyy-mm-dd"is effectively years-minutes-days.

您的格式字符串"yyyy-mm-dd"是有效的years-minutes-days

Change the format string to "yyyy-MM-dd..."and it will fix the problem.

将格式字符串更改为"yyyy-MM-dd...",它将解决问题。