Convert between String and Timestamp

Issue: BAEL-2325
This commit is contained in:
Laurentiu Delcea 2018-11-19 17:05:05 +02:00 committed by Josh Cummings
parent d751dc2eae
commit ba98695605
2 changed files with 41 additions and 0 deletions

View File

@ -0,0 +1,22 @@
package com.baeldung.timestamp;
import org.junit.Assert;
import org.junit.Test;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class StringToTimestampConverterUnitTest {
@Test
public void givenDatePattern_whenParsing_thenTimestampIsCorrect() {
String pattern = "MMM dd, yyyy HH:mm:ss.SSSSSSSS";
String timestampAsString = "Nov 12, 2018 13:02:56.12345678";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
LocalDateTime localDateTime = LocalDateTime.from(formatter.parse(timestampAsString));
Timestamp timestamp = Timestamp.valueOf(localDateTime);
Assert.assertEquals("2018-11-12 13:02:56.12345678", timestamp.toString());
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.timestamp;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import java.sql.Timestamp;
import java.time.format.DateTimeFormatter;
public class TimestampToStringConverterTest {
@Test
public void givenDatePattern_whenFormatting_thenResultingStringIsCorrect() {
Timestamp timestamp = Timestamp.valueOf("2018-12-12 01:02:03.123456789");
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
String timestampAsString = formatter.format(timestamp.toLocalDateTime());
Assert.assertEquals("2018-12-12T01:02:03.123456789", timestampAsString);
}
}