Home » Android » Android: Convert date to milliseconds

Android: Convert date to milliseconds

Posted by: admin June 15, 2020 Leave a comment

Questions:

I used

SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy, HH:mm");
String time = formatter.format(new Date());

to get the time (12.03.2012, 17:31), now i want to convert this time to milliseconds, because i have a file with a couple dates and text, and i want to convert the dates in milliseconds so that i cant add the text in inbox using

ContentValues values = new ContentValues();
values.put("address", "123");
values.put("body", "tekst");
values.put("read", 1);
values.put("date", HERE I MUST PUT A DATE IN MILLISECONDS);     
context.getContentResolver().insert(Uri.parse("content://sms/inbox"), values);

Because i must put a time in milliseconds i must convert the time, does anyone know how?

How to&Answers:

The simplest way is to convert Date type to milliseconds:

SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy, HH:mm");
formatter.setLenient(false);

Date curDate = new Date();
long curMillis = curDate.getTime();
String curTime = formatter.format(curDate);

String oldTime = "05.01.2011, 12:45";
Date oldDate = formatter.parse(oldTime);
long oldMillis = oldDate.getTime();

Answer:

Use your date object and call date.getTime()

Answer:

String Date = "Tue Apr 25 18:06:45 GMT+05:30 2017"; 
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
try {
    Date mDate = sdf.parse(Date);
    long timeInMilliseconds = mDate.getTime();

} catch (ParseException e) {
            e.printStackTrace();
}

Answer:

If you want the current time in millis just use System.currentTimeMillis()

Answer:

Use .getMillis();

e.g:

DateTime dtDate = new DateTime();
dtDate.getMillis()