get timestamp java code example

Example 1: java timestamp

Timestamp timestamp = new Timestamp(System.currentTimeMillis());
//2016-11-16 06:43:19.77
Copy

Example 2: get long from date java

String string_date = "12-December-2012";

SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy");
try {
    Date d = f.parse(string_date);
    long milliseconds = d.getTime();
} catch (ParseException e) {
    e.printStackTrace();
}

Example 3: get current date time timestamp java

// 2021-03-24 16:48:05.591
  Timestamp timestamp = new Timestamp(System.currentTimeMillis());

  // 2021-03-24 16:48:05.591
  Date date = new Date();
  Timestamp timestamp2 = new Timestamp(date.getTime());

  // convert Instant to Timestamp
  Timestamp ts = Timestamp.from(Instant.now())

  // convert ZonedDateTime to Instant to Timestamp
  Timestamp ts = Timestamp.from(ZonedDateTime.now().toInstant()));

  // convert Timestamp to Instant
  Instant instant = ts.toInstant();

Example 4: java timestamp

package com.mkyong.date;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TimeStampExample {

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");

    public static void main(String[] args) {

        //method 1
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        System.out.println(timestamp);

        //method 2 - via Date
        Date date = new Date();
        System.out.println(new Timestamp(date.getTime()));

        //return number of milliseconds since January 1, 1970, 00:00:00 GMT
        System.out.println(timestamp.getTime());

        //format timestamp
        System.out.println(sdf.format(timestamp));
        
    }

}
Copy

Example 5: java how to get current time

import java.util.Calendar;
Date currentTime = Calendar.getInstance().getTime();