Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BAEL-7614 sql.Timestamp to java.util.Calendar conversion #16607

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.baeldung.timestamptocalendar;

import java.sql.Timestamp;
import java.util.Calendar;

public class SqlTimestampToCalendarConverter {

public static Calendar timestampToCalendar(Timestamp timestamp) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timestamp.getTime());
return calendar;
}

public static Timestamp calendarToTimestamp(Calendar calendar) {
return new Timestamp(calendar.getTimeInMillis());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.baeldung.timestamptocalendar;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;

import java.sql.Timestamp;
import java.util.Calendar;

import org.junit.Test;

public class SqlTimestampToCalendarConverterUnitTest {

@Test
public void givenTimestamp_whenConvertToCalendar_thenEqualMillis() {
Timestamp timestamp = new Timestamp(1713544200801L);
Calendar calendar = SqlTimestampToCalendarConverter.timestampToCalendar(timestamp);
assertEquals(calendar.getTimeInMillis(), timestamp.getTime());
}

@Test
public void givenCalendarFromTimestamp_whenConvertBackToTimestamp_thenEqualMillis() {
Timestamp timestamp = new Timestamp(1713544200801L);
Calendar calendar = SqlTimestampToCalendarConverter.timestampToCalendar(timestamp);
timestamp = SqlTimestampToCalendarConverter.calendarToTimestamp(calendar);
assertEquals(calendar.getTimeInMillis(), timestamp.getTime());
}

@Test
public void givenTimestamp_whenConvertToCalendarAndBack_thenLoseNanos() {
int nanos = 801789562;
int losslessNanos = 801000000;
Timestamp timestamp = new Timestamp(1713544200801L);
timestamp.setNanos(nanos);
assertEquals(nanos, timestamp.getNanos());
Calendar calendar = SqlTimestampToCalendarConverter.timestampToCalendar(timestamp);
timestamp = SqlTimestampToCalendarConverter.calendarToTimestamp(calendar);
assertEquals(losslessNanos, timestamp.getNanos());
}
}