Skip to content

Instantly share code, notes, and snippets.

@sroccaserra
Created May 27, 2015 14:52
Show Gist options
  • Select an option

  • Save sroccaserra/38a4e98ae82e66150659 to your computer and use it in GitHub Desktop.

Select an option

Save sroccaserra/38a4e98ae82e66150659 to your computer and use it in GitHub Desktop.
Exploration de Java 8 java.time
package com.scratch.test;
import org.junit.Test;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.TimeZone;
import static org.fest.assertions.Assertions.assertThat;
public class Java8JavaTimeUnitTest
{
@Test
public void aJava_Util_DateIsAlmostLikeAJava_Time_InstantInUTC()
{
final Date date = new Date( 0L );
assertThat( date.getTime() ).isEqualTo( 0L );
final Instant instant = date.toInstant();
assertThat( instant.getEpochSecond() ).isEqualTo( 0 );
}
@Test
public void java_Util_DateToStringIsInconsistentWithJava_Time_InstantToString()
{
final Date date = new Date( 0L );
final Instant instant = date.toInstant();
assertThat( TimeZone.getDefault().getID() ).isEqualTo( "Europe/Paris" );
assertThat( instant.toString() ).isEqualTo( "1970-01-01T00:00:00Z" );
assertThat( date.toString() ).isEqualTo( "Thu Jan 01 01:00:00 CET 1970" );
}
@Test
public void java_Util_DateIsConvertedToStringUsingTheDefaultTimeZone()
{
final Date date = new Date( 0L );
assertThat( TimeZone.getDefault().getID() ).isEqualTo( "Europe/Paris" );
assertThat( date.toString() ).isEqualTo( "Thu Jan 01 01:00:00 CET 1970" );
}
@Test
public void java_Util_DateIsFormatedUsingTheDefaultTimeZone()
{
final Date date = new Date( 0L );
final SimpleDateFormat simpleDateFormat = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss" );
assertThat( simpleDateFormat.getTimeZone().getID() ).isEqualTo( "Europe/Paris" );
assertThat( simpleDateFormat.format( date ) ).isEqualTo( "1970-01-01T01:00:00" );
}
@Test
public void aJava_Time_InstantIsConvertedToAStringRegardlessOfTheDefaultTimeZone()
{
final Date date = new Date( 0L );
final Instant instant = date.toInstant();
assertThat( TimeZone.getDefault().getID() ).isEqualTo( "Europe/Paris" );
assertThat( instant.toString() ).isEqualTo( "1970-01-01T00:00:00Z" );
}
@Test
public void useUTCTimeZoneToConvertJava_Util_DateUsedAsTimeZoneLessDateTimeToJava_Time_LocalDateTime()
{
final Date date = new Date( 0L );
final Instant instant = date.toInstant();
final LocalDateTime localDateTime = LocalDateTime.ofInstant( instant, ZoneId.of( "UTC" ) );
assertThat( localDateTime.getHour() ).isZero();
assertThat( localDateTime.getMinute() ).isZero();
assertThat( localDateTime.getSecond() ).isZero();
assertThat( localDateTime.toString() ).isEqualTo( "1970-01-01T00:00" );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment