50

I have one date and time format as below:

Tue Apr 23 16:08:28 GMT+05:30 2013

I want to convert into milliseconds, but I actually dont know which format it is. Can anybody please help me.

Pratik Dasa
  • 7,439
  • 4
  • 30
  • 44

10 Answers10

104

Update for DateTimeFormatter introduced in API 26.

Code can be written as below for API 26 and above

// Below Imports are required for this code snippet
// import java.util.Locale;
// import java.time.LocalDateTime;
// import java.time.ZoneOffset;
// import java.time.format.DateTimeFormatter;
String date = "Tue Apr 23 16:08:28 GMT+05:30 2013";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
LocalDateTime localDate = LocalDateTime.parse(date, formatter);
long timeInMilliseconds = localDate.atOffset(ZoneOffset.UTC).toInstant().toEpochMilli();
Log.d(TAG, "Date in milli :: FOR API >= 26 >>> " + timeInMilliseconds);
// Output is -> Date in milli :: FOR API >= 26 >>> 1366733308000

But as of now only 6% of devices are running on 26 or above. So you will require backward compatibility for above classes. JakeWharton has been written ThreeTenABP which is based on ThreeTenBP, but specially developed to work on Android. Read more about How and Why ThreeTenABP should be used instead-of java.time, ThreeTen-Backport, or even Joda-Time

So using ThreeTenABP, above code can be written as (and verified on API 16 to API 29)

// Below Imports are required for this code snippet
// import java.util.Locale;
// import org.threeten.bp.OffsetDateTime;
// import org.threeten.bp.format.DateTimeFormatter;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
        "EEE MMM dd HH:mm:ss OOOO yyyy", Locale.ROOT);
String givenDateString = "Tue Apr 23 16:08:28 GMT+05:30 2013";
long timeInMilliseconds = OffsetDateTime.parse(givenDateString, formatter)
        .toInstant()
        .toEpochMilli();
System.out.println("Date in milli :: USING ThreeTenABP >>> " + timeInMilliseconds);
// Output is -> Date in milli :: USING ThreeTenABP >>> 1366713508000

Ole covered summarised information (for Java too) in his answer, you should look into.


Below is old approach (and previous version of this answer) which should not be used now

Use below method

String givenDateString = "Tue Apr 23 16:08:28 GMT+05:30 2013"; 
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
try {
    Date mDate = sdf.parse(givenDateString);
    long timeInMilliseconds = mDate.getTime();
    System.out.println("Date in milli :: " + timeInMilliseconds);
} catch (ParseException e) {
            e.printStackTrace();
}

Read more about date and time pattern strings.

Pankaj Kumar
  • 81,967
  • 29
  • 167
  • 186
  • 4
    Perfect answer. working 100% for all android platform. Keep it up bro – Pir Fahim Shah Jan 20 '18 at 09:01
  • i get a date and time from server api i tried all answer above two give me a error which is java.time.format.DateTimeParseException: Text '2021-03-05 09:18:07' could not be parsed at index 10. and last one is giving me answer 51 year ago. i dont understand why – Adnan haider Mar 06 '21 at 05:24
  • @Adnanhaider Formatter would be different for this date. – Pankaj Kumar Mar 06 '21 at 14:39
  • You can use code `coreLibraryDesugaringEnabled` which offers backward compatibility without needing third party library – Bitwise DEVS May 31 '22 at 09:04
13

try this...

Calendar calendar = Calendar.getInstance();
calendar.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth(), 
             timePicker.getCurrentHour(), timePicker.getCurrentMinute(), 0);
long startTime = calendar.getTimeInMillis();
12

You can use this code

long miliSecsDate = milliseconds ("2015-06-04");
Log.d("miliSecsDate", " = "+miliSecsDate);

    public long milliseconds(String date) 
    {
        //String date_ = date;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try
        {
            Date mDate = sdf.parse(date);
            long timeInMilliseconds = mDate.getTime();
            System.out.println("Date in milli :: " + timeInMilliseconds);
            return timeInMilliseconds;
        }
        catch (ParseException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return 0;
    }
Rumit Patel
  • 8,830
  • 18
  • 51
  • 70
M.Ganji
  • 818
  • 8
  • 13
10

In Kotlin,

Just use

timeInMilSeconds = date.time

where timeInMilSeconds is milliseconds(var timeInMilSeconds: Long) and date is Date

Kishan Solanki
  • 13,761
  • 4
  • 85
  • 82
2
Date beginupd = new Date(cursor1.getLong(1));

This variable beginupd contains the format

Wed Oct 12 11:55:03 GMT+05:30 2011

long millisecond = beginupd.getTime();

Date.getTime() JavaDoc states:

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

kalyan pvs
  • 14,486
  • 4
  • 41
  • 59
2

Covert date and time string to milliseconds:

 public static final String DATE_TIME_FORMAT = "MM/dd/yyyy HH:mm:ss a";

or

  public static final String DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";

or

  public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ssZZZZZ";
  //TimeZone.getAvailableIds() to list all timezone ids
  String timeZone = "EST5EDT";//it can be anything timezone like IST, GMT.
  String time = "2/21/2018 7:41:00 AM";

 public static long[] convertTimeInMillis(String dateTimeFormat, String timeZone, String... times) throws ParseException {

   SimpleDateFormat dateFormat = new SimpleDateFormat(dateTimeFormat, Locale.getDefault());
   dateFormat.setTimeZone(TimeZone.getTimeZone(timeZone));
   long[] ret = new long[times.length];
   for (int i = 0; i < times.length; i++) {
      String timeWithTZ = times[i] + " "+timeZone;
      Date d = dateFormat.parse(timeWithTZ);
      ret[i] = d.getTime();
    }
  return ret;

}

//millis to dateString

  public static String convertTimeInMillisToDateString(long timeInMillis, String DATE_TIME_FORMAT) {
     Date d = new Date(timeInMillis);
     SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
     return sdf.format(d);
  }
Naresh Palle
  • 339
  • 3
  • 8
2

java.time and ThreeTenABP

I am providing the modern answer — though not more modern than it works on your Android API level too.

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
            "EEE MMM dd HH:mm:ss OOOO yyyy", Locale.ROOT);
    String givenDateString = "Tue Apr 23 16:08:28 GMT+05:30 2013";
    long timeInMilliseconds = OffsetDateTime.parse(givenDateString, formatter)
            .toInstant()
            .toEpochMilli();
    System.out.println(timeInMilliseconds);

Output from this snippet is:

1366713508000

The SimpleDateFormat, Date and Calendar classes used in most of the other answers are poorly designed and now long outdated. I recommend that instead you use java.time, the modern Java date and time API. Edit: The other answers were fine answers when the question was asked in 2013. Only time moves on, and we should not use SimpleDateFormat, Date and Calendar any more.

Question: Doesn’t java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
1

Try this in Kotlin,

val calendar = Calendar.getInstance()
val UniqueID = calendar.timeInMillis

same code in Java,

Calendar calendar = Calendar.getInstance(); long time = calendar.getTimeInMillis();
Rajesh Naddy
  • 1,120
  • 12
  • 17
1

Android 26 and higher

Conversation from epoch to UTC date time and Device date time

public class TimeConversionUtil {

public static long getCurrentEpochUTC() {
    return Instant.now(Clock.systemUTC()).toEpochMilli();
}

public static String deviceDateTimeString(long epochMilliUtc) {
    Instant instant = Instant.ofEpochMilli(epochMilliUtc);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd, yyyy, hh:mm:ss a", Locale.US).withZone(ZoneId.systemDefault());
    return formatter.format(instant);
}

public static String uTCDateTimeString(long epochMilliUtc) {
    Instant instant = Instant.ofEpochMilli(epochMilliUtc);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd, yyyy, hh:mm:ss a", Locale.US).withZone(ZoneId.of("UTC"));
    return formatter.format(instant);

}

public static long convertDateStringToLongUTC(String stringUTCDate) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd, yyyy, hh:mm:ss a", Locale.ENGLISH);
    LocalDateTime localDate = LocalDateTime.parse(stringUTCDate, formatter);
    long timeInMilliseconds = localDate.atOffset(ZoneOffset.UTC).toInstant().toEpochMilli();
    return timeInMilliseconds;
}

}

@Test
public void timeConversionTest() {
    long currentTimeUtc = Instant.now(Clock.systemUTC()).toEpochMilli();
    String utc = TimeConversionUtil.uTCDateTimeString(currentTimeUtc);
    Long utcLongTime = TimeConversionUtil.convertDateStringToLongUTC(utc);
    String utc1 = TimeConversionUtil.uTCDateTimeString(utcLongTime);
    assertTrue(utc.equalsIgnoreCase(utc1));
}
Jawad
  • 308
  • 3
  • 12
0

Just to complement the given answers, if you need to convert the time given by the date to other time units you can use the TimeUnit API

Example:

TimeUnit.MILLISECONDS.toMinutes(millis)
André Sousa
  • 1,692
  • 1
  • 12
  • 23