[英]Java: Convert String to TimeStamp
我在嘗試將字符串轉換為時間戳時遇到問題。 我有一個數組,其日期格式為yyyy-MM-dd
,我想更改為yyyy-MM-dd HH:mm:ss.SSS
。 所以,我使用這個代碼:
final String OLD_FORMAT = "yyyy-MM-dd";
final String NEW_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
String oldDateString = createdArray[k];
String newDateString;
DateFormat formatter = new SimpleDateFormat(OLD_FORMAT);
Date d = formatter.parse(oldDateString);
((SimpleDateFormat) formatter).applyPattern(NEW_FORMAT);
newDateString = formatter.format(d);
System.out.println(newDateString);
Timestamp ts = Timestamp.valueOf(newDateString);
System.out.println(ts);
我得到以下結果。
2009-10-20 00:00:00.000
2009-10-20 00:00:00.0
但是當我試着簡單地做
String text = "2011-10-02 18:48:05.123";
ts = Timestamp.valueOf(text);
System.out.println(ts);
我得到正確的結果:
2011-10-02 18:48:05.123
你知道我可能做錯了什么嗎? 謝謝您的幫助。
請按照以下步驟獲得正確的結果:
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
Date parsedDate = dateFormat.parse(yourString);
Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
} catch(Exception e) { //this generic but you can control another types of exception
// look the origin of excption
}
請注意.parse(String)
可能會拋出ParseException
。
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Util {
public static Timestamp convertStringToTimestamp(String strDate) {
try {
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
// you can change format of date
Date date = formatter.parse(strDate);
Timestamp timeStampDate = new Timestamp(date.getTime());
return timeStampDate;
} catch (ParseException e) {
System.out.println("Exception :" + e);
return null;
}
}
}
我想貢獻現代答案。 當在 2013 年提出這個問題時,使用Timestamp
類是正確的,例如將日期時間存儲到您的數據庫中。 今天的課程已經過時了。 現代 Java 日期和時間 API 於 2014 年春季(三年半前)隨 Java 8 發布。 我建議你改用這個。
根據您的情況和確切要求, Timestamp
有兩種自然替代品:
Instant
是時間線上的一個點。 對於大多數目的,我認為使用它是最安全的。 Instant
與時區無關,即使在您的客戶端設備和數據庫服務器運行不同時區的情況下,它通常也能很好地工作。LocalDateTime
是沒有時區的日期和時間,例如 2011-10-02 18:48:05.123(引用問題)。 現代 JDBC 驅動程序(JDBC 4.2 或更高版本)和其他用於數據庫訪問的現代工具很樂意將Instant
或LocalDateTime
存儲到數據類型為timestamp
數據庫列中。 我在此答案中使用的類和其他日期時間類都屬於稱為java.time
或 JSR-310 的現代 API。
將字符串轉換為LocalDateTime
是最簡單的,所以讓我們先來看看:
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS");
String text = "2011-10-02 18:48:05.123";
LocalDateTime dateTime = LocalDateTime.parse(text, formatter);
System.out.println(dateTime);
這打印
2011-10-02T18:48:05.123
如果您的字符串是 yyyy-MM-dd 格式,請改為:
String text = "2009-10-20";
LocalDateTime dateTime = LocalDate.parse(text).atStartOfDay();
System.out.println(dateTime);
這打印
2009-10-20T00:00
或者更好的是,從LocalDate.parse()
獲取輸出並將其存儲到數據類型為date
的數據庫列中。
在這兩種情況下,從LocalDateTime
轉換為Instant
是:
Instant ts = dateTime.atZone(ZoneId.systemDefault()).toInstant();
System.out.println(ts);
我已經使用 JVM 的默認時區指定了一個轉換,因為這是過時的類將使用的。 但是,這很脆弱,因為程序的其他部分或在同一 JVM 中運行的其他程序可能會更改時區設置。 如果可以,請改為以地區/城市格式指定時區,例如:
Instant ts = dateTime.atZone(ZoneId.of("Europe/Athens")).toInstant();
將 String 轉換為 java.sql.Timestamp 的簡單方法:
Timestamp t = new Timestamp(DateUtil.provideDateFormat().parse("2019-01-14T12:00:00.000Z").getTime());
DateUtil.java:
import java.text.SimpleDateFormat;
import java.util.TimeZone;
public interface DateUtil {
String ISO_DATE_FORMAT_ZERO_OFFSET = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
String UTC_TIMEZONE_NAME = "UTC";
static SimpleDateFormat provideDateFormat() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(ISO_DATE_FORMAT_ZERO_OFFSET);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone(UTC_TIMEZONE_NAME));
return simpleDateFormat;
}
}
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = formatter.parse(dateString);
Timestamp timestamp = new Timestamp(date.getTime());
System.out.println(timestamp);
為了完整起見,這里有一個帶有 lambda 和方法參考的解決方案:
說明:以下方法
yyyy-MM-dd
模式的String
轉換為Timestamp
,null
,如果給定一個null
值,DateTimeParseException
代碼:
static Timestamp convertStringToTimestamp(String strDate) {
return Optional.ofNullable(strDate) // wrap the String into an Optional
.map(str -> LocalDate.parse(str).atStartOfDay()) // convert into a LocalDate and fix the hour:minute:sec to 00:00:00
.map(Timestamp::valueOf) // convert to Timestamp
.orElse(null); // if no value is present, return null
}
驗證:可以使用這些單元測試來測試此方法:(使用Junit5和Hamcrest )
@Test
void convertStringToTimestamp_shouldReturnTimestamp_whenValidInput() {
// given
String strDate = "2020-01-30";
// when
final Timestamp result = convertStringToTimestamp(strDate);
// then
final LocalDateTime dateTime = LocalDateTime.ofInstant(result.toInstant(), ZoneId.systemDefault());
assertThat(dateTime.getYear(), is(2020));
assertThat(dateTime.getMonthValue(), is(1));
assertThat(dateTime.getDayOfMonth(), is(30));
}
@Test
void convertStringToTimestamp_shouldReturnTimestamp_whenInvalidInput() {
// given
String strDate = "7770-91-30";
// when, then
assertThrows(DateTimeParseException.class, () -> convertStringToTimestamp(strDate));
}
@Test
void convertStringToTimestamp_shouldReturnTimestamp_whenNullInput() {
// when
final Timestamp result = convertStringToTimestamp(null);
// then
assertThat(result, is(nullValue()));
}
通常,要解析的字符串帶有另一種格式。 處理它的一種方法是使用格式化程序將其轉換為另一種格式。 下面是一個例子:
輸入: 20200130 11:30
圖案: yyyyMMdd HH:mm
輸出:此輸入的時間戳
代碼:
static Timestamp convertStringToTimestamp(String strDate) {
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm");
return Optional.ofNullable(strDate) //
.map(str -> LocalDateTime.parse(str, formatter))
.map(Timestamp::valueOf) //
.orElse(null);
}
測試:
@Test
void convertStringToTimestamp_shouldReturnTimestamp_whenValidInput() {
// given
String strDate = "20200130 11:30";
// when
final Timestamp result = convertStringToTimestamp(strDate);
// then
final LocalDateTime dateTime = LocalDateTime.ofInstant(result.toInstant(), ZoneId.systemDefault());
assertThat(dateTime.getYear(), is(2020));
assertThat(dateTime.getMonthValue(), is(1));
assertThat(dateTime.getDayOfMonth(), is(30));
assertThat(dateTime.getHour(), is(11));
assertThat(dateTime.getMinute(), is(30));
}
DateFormat formatter;
formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = (Date) formatter.parse(str_date);
java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());
首先將您的日期字符串轉換為date
然后使用以下一組行將其轉換為timestamp
Date date=new Date();
Timestamp timestamp = new Timestamp(date.getTime());//instead of date put your converted date
Timestamp myTimeStamp= timestamp;
你能不能試一次...
String dob="your date String";
String dobis=null;
final DateFormat df = new SimpleDateFormat("yyyy-MMM-dd");
final Calendar c = Calendar.getInstance();
try {
if(dob!=null && !dob.isEmpty() && dob != "")
{
c.setTime(df.parse(dob));
int month=c.get(Calendar.MONTH);
month=month+1;
dobis=c.get(Calendar.YEAR)+"-"+month+"-"+c.get(Calendar.DAY_OF_MONTH);
}
}
我確定解決方案是您的 oldDateString 類似於“2009-10-20”。 顯然,這不包含任何低於天的時間數據。 如果你用你的新格式化程序格式化這個字符串,它應該從哪里獲取分鍾、秒和毫秒?
所以結果是絕對正確的:2009-10-20 00:00:00.000
您需要解決這個問題,是您第一次格式化之前的原始時間戳(包括時間數據)。
這就是我所做的:
Timestamp timestamp = Timestamp.valueOf(stringValue);
其中stringValue
可以是任何日期/時間格式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.