Skip to content Skip to sidebar Skip to footer

How To Get A Formatted Date As Milliseconds?

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 millisec

Solution 1:

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

Solution 2:

Use date.getTime()

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


StringoldTime="2012-07-11 10:55:21";
DateoldDate= formatter.parse(oldTime);
longoldMillis= oldDate.getTime();

Solution 3:

try this:

import java.util.*;


publicclassConvertDateIntoMilliSecondsExample{

publicstaticvoidmain(String args[]){

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

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

    }

}

Solution 4:

java.time

Solution using java.time, the modern date-time API

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

publicclassMain {
    publicstaticvoidmain(String[] args) {
        // Test
        System.out.println(toMillis("2012-07-11 10:55:21"));
    }

    publicstaticlongtoMillis(String strDateTime) {
        // Replace the parameter, ZoneId.systemDefault() which returns JVM's default// timezone, as applicable e.g. to ZoneId.of("America/New_York")DateTimeFormatterdtf= DateTimeFormatter.ofPattern("u-M-d H:m:s", Locale.ENGLISH)
                                    .withZone(ZoneId.systemDefault());

        ZonedDateTimezdt= ZonedDateTime.parse(strDateTime, dtf);
        
        Instantinstant= zdt.toInstant();
        
        return instant.toEpochMilli();
    }
}

Output:

1342000521000

Learn more about the the modern date-time API* from Trail: Date Time.


*For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Post a Comment for "How To Get A Formatted Date As Milliseconds?"