Home » Android » java – how to get a formatted date as milliseconds?

java – how to get a formatted date as milliseconds?

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have a formatted date from sqllite database, to use this in a graph view I need to format it in a long number.

The format is:

2012-07-11 10:55:21

how can I convert it to milliseconds?

How to&Answers:

You can convert the string into a Date object using this code:-

Date d = DateFormat.parse(String s)

And then convert it into milliseconds by using the inbuilt method

long millisec = d.getTime();

Answer:

Use date.getTime()

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


String oldTime = "2012-07-11 10:55:21";
Date oldDate = formatter.parse(oldTime);
long oldMillis = oldDate.getTime();

Answer:

try this:

import java.util.*;


public class ConvertDateIntoMilliSecondsExample{

public static void main(String args[]){

//create a Date object  
Date date = new Date();
System.out.println("Date is : " + date);

//use getTime() method to retrieve milliseconds
System.out.println("Milliseconds since January 1, 1970, 00:00:00 GMT : "
                  + date.getTime());

    }

}