1

I am trying to Convert date and time i am receiving in MM/dd/yyyy hh:mm a format to milliseconds so that i can push the date as end date in google calendar. I am trying below code but i am getting error.

Code:

String myDate = "10/20/2017 8:10 AM";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
Date date = sdf.parse(myDate);
long millis = date.getTime();

Error:

java.text.ParseException: Unparseable date: "10/20/2017 8:10 AM" (at offset 16)
Ironman
  • 1,330
  • 2
  • 19
  • 40

3 Answers3

3

Try this .

String myDate = "10/20/2017 8:10 AM";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy h:mm a", Locale.ENGLISH);
Date date = sdf.parse(myDate);
long millis = date.getTime();

Add Locale.ENGLISH in your code .

KeLiuyue
  • 8,149
  • 4
  • 25
  • 42
0

Your code seems to be OK, i've just added try/catch block:

try {
    String myDate = "10/20/2017 8:10 AM";
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
    Date date = sdf.parse(myDate);
    long millis = date.getTime();

    System.out.println(date);
    System.out.println(millis);
    }
    catch(Exception ex) {
        System.out.println(ex);
    }

This code prints 1508479800000 as millis. If you want to check it backwards try this:

String x = "1508479800000";

            DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm a");

            long milliSeconds= Long.parseLong(x);
            System.out.println(milliSeconds);

            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(milliSeconds);
            System.out.println(formatter.format(calendar.getTime())); 

this will give you 10/20/2017 08:10 AM.

Stanojkovic
  • 1,612
  • 1
  • 17
  • 24
-1

You can use SimpleDateFormat to do it. You just have to know 2 things.

All dates are internally represented in UTC .getTime() returns the number of milliseconds since 1970-01-01 00:00:00 UTC. package se.wederbrand.milliseconds;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class Main {        
    public static void main(String[] args) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

        String inputString = "00:01:30.500";

        Date date = sdf.parse("1970-01-01 " + inputString);
        System.out.println("in milliseconds: " + date.getTime());        
    }
}

by this one https://stackoverflow.com/a/8826392/8456432