gpt4 book ai didi

java - 是否可以不使用格式解析将字符串转换为日期或时间戳

转载 作者:行者123 更新时间:2023-11-30 03:49:31 24 4
gpt4 key购买 nike

String string_Date = "2014-06-11"; //my string date 
SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
// Date startTimestam = simpleFormat.parse(string_Date);
Timestamp startTimestam = Timestamp.valueOf(string_Date);
Calendar cal = Calendar.getInstance();
cal.setTime(startTimestam);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 1);
starTimeStamp = new Timestamp(cal.getTime().getTime());
// will get output date is "2014-06-11 00:00:01"

  • 这里我不想使用简单的格式将字符串转换为日期或时间戳,
  • 如果运行上面的代码,我将得到异常 illegalArgumentException

    Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]**

  • 是否可以不使用格式转换字符串日期。
  • 如果可能的话对我很有帮助。

最佳答案

您的问题不太清楚,原因如下:

1) 为什么要避免使用 SimpleDateFormat?

2) 您想要将字符串转换为时间戳还是将日期转换为时间戳?

如果你想将字符串转换为时间戳,那么它很简单(不使用 SimpleDateFormat):

String timeValueStr="00:00:01";
String startTimeStr="2014-06-11" + " " + timeValueStr;
Timestamp startTimestamp = Timestamp.valueOf(startTimeStr);

如果要将字符串转换为日期,然后将日期转换为时间戳:

//String to Date conversion
String startTimeStr = "2014-06-11";
SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
Date d = simpleFormat.parse(startTimeStr);
//Date to Timestamp conversion
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 1);
Timestamp startTimestamp = new Timestamp(cal.getTime().getTime());

当然,如果您必须避免使用 SimpleDateFormat,那么这里是先将 String 转换为 Timestamp,然后再转换为 Date 的代码(如果不使用 SimpleDateFormat,则无法直接将 String 转换为 Date):

String timeValueStr="00:00:01";
String startTimeStr="2014-06-11" + " " + timeValueStr;
Timestamp startTimestamp = Timestamp.valueOf(startTimeStr);
Date d = new Date(startTimestamp.getTime());

关于java - 是否可以不使用格式解析将字符串转换为日期或时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24775294/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com