Saturday 20 August 2022

Java: Get milliseconds from given date and time

Step 1: Get the SimpleDateFormat instance from given date pattern.

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");

 

Step 2: Get the Date object by parsing given date string.

Date date = simpleDateFormat.parse("22-8-2021 8:32:15");

 

Step 3: Get the time in milliseconds.

long timeInMillis = date.getTime();

Find the below working application.

 


DateToMillis.java

package com.sample.app;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateToMillis {

    private static long timeInMillis(String dateString, String datePattern) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(datePattern);
        Date date = simpleDateFormat.parse(dateString);
        return date.getTime();
    }

    public static void main(String[] args) throws ParseException {
        long timeMillis1 = timeInMillis("22-8-2021 8:32:15", "dd-M-yyyy hh:mm:ss");
        System.out.println("timeMillis1: " + timeMillis1);
    }

}

Output

timeMillis1: 1629601335000



Previous                                                 Next                                                 Home

No comments:

Post a Comment