Created
August 27, 2013 18:40
-
-
Save dustin-graham/6357359 to your computer and use it in GitHub Desktop.
handy tool for working with time strings
This file contains 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
package com.ifit.android.sdk.util; | |
import java.text.DateFormat; | |
import java.text.ParseException; | |
import java.text.SimpleDateFormat; | |
import java.util.Calendar; | |
import java.util.Date; | |
import java.util.GregorianCalendar; | |
import java.util.Locale; | |
import java.util.TimeZone; | |
public class DateHelper { | |
public static String iso8601DateFormat; | |
private static TimeZone mUTCTimeZone; | |
public DateHelper() { | |
} | |
static { | |
iso8601DateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; | |
mUTCTimeZone = TimeZone.getTimeZone("UTC"); | |
} | |
/* | |
* iso8601Date parameter must be "yyyy-MM-dd HH:mm:ss.SSSZ" formatted date | |
* dates are returned in the UTC time zone time. returns null for parse | |
* exceptions | |
*/ | |
public static Date dateFromISO8601(String iso8601Date) { | |
if (iso8601Date == null) | |
return null; | |
try { | |
DateFormat dateFormat = new SimpleDateFormat(iso8601DateFormat, | |
Locale.US); | |
dateFormat.setTimeZone(mUTCTimeZone); | |
return dateFormat.parse(iso8601Date); | |
} catch (ParseException e) { | |
e.printStackTrace(); | |
} | |
return null; | |
} | |
/* | |
* takes a date and returns a "yyyy-MM-dd HH:mm:ss.SSSZ" formatted string. | |
* The time zone for this string is UTC. This format must be used when | |
* storing and transferring dates. for local formatted date strings, use | |
* another method | |
*/ | |
public static String iso8601FormattedStringFromDate(Date date) { | |
DateFormat dateFormat = new SimpleDateFormat(iso8601DateFormat, | |
Locale.US); | |
dateFormat.setTimeZone(mUTCTimeZone); | |
return dateFormat.format(date); | |
} | |
public enum TimestampType { | |
SecondsSinceEpoc, MillisSinceEpoc | |
} | |
public static String iso8601FormattedStringFromTimestamp(long timestamp, | |
TimestampType timestampType) { | |
if (timestampType == TimestampType.SecondsSinceEpoc) { | |
timestamp = timestamp * 1000; | |
} | |
Date date = new Date(timestamp); | |
return iso8601FormattedStringFromDate(date); | |
} | |
public static long getTodayMillis() { | |
Calendar c = new GregorianCalendar(); | |
c.set(Calendar.HOUR_OF_DAY, 0); //anything 0 - 23 | |
c.set(Calendar.MINUTE, 0); | |
c.set(Calendar.SECOND, 0); | |
c.set(Calendar.MILLISECOND, 0); | |
return c.getTimeInMillis(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment