Pratik Dasa
Pratik Dasa

Reputation: 7439

Android convert date and time to milliseconds

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.

Upvotes: 50

Views: 122553

Answers (10)

Kishan Solanki
Kishan Solanki

Reputation: 14618

In Kotlin,

Just use

timeInMilSeconds = date.time

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

Upvotes: 11

Jawad
Jawad

Reputation: 308

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));
}

Upvotes: 1

Pankaj Kumar
Pankaj Kumar

Reputation: 82938

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.

Upvotes: 104

Anonymous
Anonymous

Reputation: 86139

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

Upvotes: 2

M.Ganji
M.Ganji

Reputation: 866

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;
    }

Upvotes: 12

André Sousa
André Sousa

Reputation: 1730

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)

Upvotes: 0

Rajesh Naddy
Rajesh Naddy

Reputation: 1105

Try this in Kotlin,

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

same code in Java,

Calendar calendar = Calendar.getInstance(); long time = calendar.getTimeInMillis();

Upvotes: 1

Naresh Palle
Naresh Palle

Reputation: 369

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);
  }

Upvotes: 2

user6602265
user6602265

Reputation:

try this...

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

Upvotes: 13

kalyan pvs
kalyan pvs

Reputation: 14590

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.

Upvotes: 2

Related Questions