I created 2 methods that are flexible enough to handle any date format in any time zone.
The first method is from the date String to Millis (Epoch)
//dateString to long private static long formatterDateToMillis(String dateString, String format, String timeZone){ //define Timezone, in your case you hardcoded "PST8PDT" for PST DateTimeZone yourTimeZone = DateTimeZone.forID(timeZone); //define your pattern DateTimeFormatter customFormat = DateTimeFormat.forPattern(format).withZone(yourTimeZone); //parse dateString to the format you wanted DateTime dateTime = customFormat.parseDateTime(dateString); //return in Millis, usually in epoch return dateTime.getMillis(); }
The second method is from the string Millis to Date
//dateInMillis to date format yyyy-MM-dd private static String formatterMillistoDate(long dateInMillis, String format, String timeZone){ //define your format DateTimeFormatter customFormat = DateTimeFormat.forPattern(format); //convert to DateTime with your desired TimeZone DateTime dateTime = new DateTime(dateInMillis, DateTimeZone.forID(timeZone)); //return date String in format you defined return customFormat.print(dateTime); }
Try these inputs for your main () method:
long valueInMillis = formatterDateToMillis("2015-03-17","yyyy-MM-dd","PST8PDT"); System.out.println(valueInMillis); String formattedInDate = formatterMillistoDate(1426575600000L,"yyyy-MM-dd","PST8PDT"); System.out.println(formattedInDate);
You should get the following output:
1426575600000
2015-03-17
Hope this helps !;)
source share