Skip to content

Commit ba98695

Browse files
laurentiudjzheaux
authored andcommitted
Convert between String and Timestamp
Issue: BAEL-2325
1 parent d751dc2 commit ba98695

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package com.baeldung.timestamp;
2+
3+
import org.junit.Assert;
4+
import org.junit.Test;
5+
6+
import java.sql.Timestamp;
7+
import java.time.LocalDateTime;
8+
import java.time.format.DateTimeFormatter;
9+
10+
public class StringToTimestampConverterUnitTest {
11+
12+
@Test
13+
public void givenDatePattern_whenParsing_thenTimestampIsCorrect() {
14+
String pattern = "MMM dd, yyyy HH:mm:ss.SSSSSSSS";
15+
String timestampAsString = "Nov 12, 2018 13:02:56.12345678";
16+
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
17+
LocalDateTime localDateTime = LocalDateTime.from(formatter.parse(timestampAsString));
18+
19+
Timestamp timestamp = Timestamp.valueOf(localDateTime);
20+
Assert.assertEquals("2018-11-12 13:02:56.12345678", timestamp.toString());
21+
}
22+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.baeldung.timestamp;
2+
3+
import org.junit.Assert;
4+
import org.junit.jupiter.api.Test;
5+
6+
import java.sql.Timestamp;
7+
import java.time.format.DateTimeFormatter;
8+
9+
public class TimestampToStringConverterTest {
10+
11+
@Test
12+
public void givenDatePattern_whenFormatting_thenResultingStringIsCorrect() {
13+
Timestamp timestamp = Timestamp.valueOf("2018-12-12 01:02:03.123456789");
14+
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
15+
16+
String timestampAsString = formatter.format(timestamp.toLocalDateTime());
17+
Assert.assertEquals("2018-12-12T01:02:03.123456789", timestampAsString);
18+
}
19+
}

0 commit comments

Comments
 (0)