Skip to content

Instantly share code, notes, and snippets.

@XavierTalpe
Created July 7, 2013 13:00
Show Gist options
  • Select an option

  • Save XavierTalpe/5943402 to your computer and use it in GitHub Desktop.

Select an option

Save XavierTalpe/5943402 to your computer and use it in GitHub Desktop.
Demonstrates how to encode and decode datetime strings in ISO format, such that they can be stored in a SQL database.
public final class DateUtil {
private DateUtil() {
}
public static String toIsoString( Date aDate ) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ssZ" );
return simpleDateFormat.format( aDate );
}
public static Timestamp fromIsoString( String aDate ) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ssZ" );
try {
Date parse = simpleDateFormat.parse( aDate );
return new Timestamp( parse.getTime() );
} catch ( ParseException aException ) {
aException.printStackTrace();
return null;
}
}
public static Timestamp getCurrentDateTime() {
return new Timestamp( System.currentTimeMillis() );
}
}
public class DateUtilTest {
@Test
public void testDateParsing() throws Exception {
String inputDate = "2013-06-24T15:45:00+0300";
Timestamp parsedDate = DateUtil.fromIsoString( inputDate );
String outputDate = DateUtil.toIsoString( parsedDate );
assertEquals( inputDate, outputDate );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment