Created
July 7, 2013 13:00
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() ); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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