current timestamp in Java

In Java, getting the current timestamp is simple. We’ll learn how to acquire the timestamp using the Date and Timestamp classes in this lesson. This article provides some Java examples for obtaining the current date, time, or timestamp. In addition, Java 8 has been included.

The timestamp represents the date and time of an occurrence. It can be the date and time when a particular input or output was made or any other internal computer event, such as adding specific data into a database in computers. Now’s timestamp is the current timestamp. If an event occurs now and the timestamp is recorded, the timestamp will be that of yesterday tomorrow.

A local timestamp, GMT timestamp, and UTC timestamp are all available. The local timestamp is the date-time used for your nation’s legal, commercial, and social purposes. The reference for GMT and UTC timestamps is the same. A time zone is a country offset that can be applied to UTC to get your local time. A time zone of +03:30 signifies that the UTC has been extended by 3 hours and 30 minutes.

The year, month, and day of the month are all included in the date portion of the timestamp. The timestamp’s time component includes at least the hour, minutes, and seconds. Milliseconds and the time zone might also be included (offset). Note that 1 ms = 1/1000 s. Therefore, the computer should provide the timestamp. As a result, the system clock must be accurate. java.time is the class. In today’s Java, instant should be used to get the timestamp.

java.time.Instant

Java has a class called java.time.The instant was explicitly created for timestamps. There are two required methods in the Instant class: now () and toString (). The timestamp object is returned by “Now.” The timestamp’s string format is produced by toString(). The following program demonstrates their application:

import java.time.Instant;

public class CodeInstant {

public static void main(String[] args) {

Instant timestamp_object = Instant.now();

String timestamp_string = timestamp_object.toString();

System.out.println(timestamp_string);

}

}

The program starts with the Instant class from java.time package being imported. Then there’s the main class’s definition (implementation). The first statement in the main() method calls the Instant class’s now() method. Now() is a static method, which means it doesn’t require the instantiated object to work. It returns the timestamp object of its Instant class by using the Instant class name. The timestamp Instant object’s toString() method returns the timestamp object’s readable string in ISO-8601 format. The computer generates the following output at the time when run:

2022-05-22T11:53:15.271438Z

This needs further explanation. The first four digits represent the event’s year. It is separated from the following two numerals, the month of the event, by a hyphen. The latter is separated from the next two digits, the day of the month of the event, by a hyphen. A timestamp comprises two parts: the date and the time. The ‘T’ separates the date and time sections. The time section starts with two digits (24-hour clock), the event’s hour. It is separated from the following two digits, which represent the minutes of the occurrence, by a colon.

It is followed by a colon, which separates it from the following two numerals, representing the event’s seconds. There are also the dot and microseconds to consider. The timestamp has no offset if it is Z. Note that toString() is a dynamic method. To work, it requires an initialized Instant object. It also gives you a string that you can save (in a database).

Epoch of Java

In Java, time is calculated using the UNIX Epoch. 1970-01-01T00:00:00Z is the UNIX Epoch.

The number of seconds since the Java Epoch

Since Java Epoch, the following application calculates the number of seconds:

import java.time.Instant;

public class CodeInstant {

public static void main(String[] args) {

Instant timestampObj = Instant.now();

long codeSecs = timestampObj.getEpochSecond();

System.out.println(codeSecs);

}

}

The getEpochSecond() function of the Instant object is used. It gives back a long integer.

instant minusSeconds(long secondsToSubtract)

With several seconds subtracted, the current date-time can be returned. It will produce a datetime before now. It is demonstrated in the following program:

import java.time.Instant;

public class CodeInstant {

public static void main(String[] args) {

Instant instantObject = Instant.now();

Instant codeObject = instantObject.minusSeconds(1000000000);

String codeStr = codeObject.toString();

System.out.println(codeStr);

}

}

Before subtracting the number of seconds, you must collect the current timestamp object. The following is the main method used:

minusSeconds(long secondsToSubtract)

It only works with immediate objects, not instant classes (name).

plusSeconds (long secondsToAdd)

With several seconds appended, the current date-time can be returned. After that, you’ll have datetime. It is demonstrated in the following program:

import java.time.Instant;

public class CodeInstant {

public static void main(String[] args) {

Instant codeInstObject = Instant.now();

Instant codeSbObj = codeInstObject.plusSeconds(1000000);

String codeStr = codeSbObj.toString();

System.out.println(codeStr);

}

}

You must obtain the current timestamp object before the amount of seconds is added. The following is the main method used:

plusSeconds(long secondsToAdd)

It only works with immediate objects, not instant classes (name).

Instant Class’s Static Properties

EPOCH, MAX, and MIN are the Instant class’s static attributes (fields). The instantiated object is not required to access a static property. It works with the name of the class. EPOCH is,

import java.time.Instant;

public class CodeInstant {

public static void main(String[] args) {

Instant codeInstObject = Instant.EPOCH;

String codeStr = codeInstObject.toString();

System.out.println(codeStr);

}

}

As expected, the resultant output is, 1970-01-01T00:00:00Z

MAX gives the maximum supported Instant. The value for MAX is output in string form using the following program:

import java.time.Instant;

public class CodeInstant {

public static void main(String[] args) {

Instant codeInstantObject = Instant.MAX;

String codeStr = codeInstantObject.toString();

System.out.println(codeStr);

}

}

MIN returns the slightest supported Instant. The value for MIN is output in string form using the following program:

import java.time.Instant;

public class CodeInstant {

public static void main(String[] args) {

Instant codeInstantObject = Instant.MIN;

String codeStr = codeInstantObject.toString();

System.out.println(codeStr);

}

}

Using Java’s Timestamp Class to Get the Current Timestamp

The Timestamp class in Java is used to get the current timestamp. We pass the time in milliseconds because this class does not have a default constructor. We use the System class’s currentTimeMillis() method to get the time. Consider the following example.

import java.sql.Timestamp;

public class CodeTimestamp {

    public static void main(String[] args) {

        Long date_time = System.currentTimeMillis();
        Timestamp codeTimestamp = new Timestamp(ate_time);
        System.out.println("The Current Time Stamp: "+codeTimestamp);
    }
}

Using Java’s Date Class, get the current timestamp

We can utilize the util package’s Date class to acquire the current timestamp. The SimpleDateFormat class is used to format the timestamp in the yyyy.MM.dd format. Consider the following example.

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

public class CodeSimpleDateFormat{

    public static void main(String[] args) {

        SimpleDateFormat codeDate = new SimpleDateFormat("yyyy.MM.dd.HH:mm:ss");
        String codeTimeStamp = codeDate.format(new Date());
        System.out.println("The Current Time Stamp is: "+codeTimeStamp);
    }
}

Java’s uses the ZonedDateTime class to get the current Timestamp

The Java datetime package’s ZonedDateTime class generates a timestamp with zone information. We get the system’s default zone using the systemDefault() function of ZoneId, and we get the current timestamp with the supplied zoneId using the now() method. After obtaining the current timestamp, we utilize the DateTimeFormatter class’s ofPattern() function to get the timestamp in a particular format. Consider the following example.

import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class CodeZonedDateTime{

    public static void main(String[] args) {

        ZoneId codeZid = ZoneId.systemDefault();
        ZonedDateTime dateTime = ZonedDateTime.now(codeZid);
        System.out.println("The Current Time Stamp is: "+dateTime);

        // formatting into a specific format
        DateTimeFormatter codeFormatter = DateTimeFormatter.ofPattern( "uuuu.MM.dd.HH:mm:ss" );
        String codeTimeStamp = datetime.format(codeFormatter);
        System.out.println("The Current Time Stamp is: "+codeTimeStamp);
    }
}

Java’s use of the LocalDateTime class to get the current timestamp

Using Java 8, you can acquire the current timestamp by using the LocalDateTime class. Consider the following example.

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class CodeLocalDateTime{

    public static void main(String[] args) {

        LocalDateTime codeDateTime = LocalDateTime.now();
        System.out.println("The Current Time Stamp's Default Format is: "+codeDateTime);
        String codeTimeStamp = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(codeDateTime);
        System.out.println("The Current Time Stamp is: "+codeTimeStamp);
    }
}

Java’s use of the Instant Class to get the current timestamp

The current timestamp can be obtained using the Instant class. To get the current timestamp in instants, we use the now() function of the Instant class.

import java.time.Instant;

public class CodeInstant{

    public static void main(String[] args) {
        Instant codeTimeStamp = Instant.now();
        System.out.println(" Your Current Default Format Time Stamp is: "+codeTimeStamp);
    }
}

Using Java’s Timestamp Class to Get the Current Timestamp

The Timestamp and Instant classes provide another way to obtain the current timestamp in Java. Consider the following example.

import java.sql.Timestamp;
import java.time.Instant;

public class CodeTimestamp {

    public static void main(String[] args) {

        long codeTime = System.currentTimeMillis();
        Timestamp codeTimestamp = new Timestamp(codeTime);
        Instant codeInstant = codeTimestamp.toInstant();
        System.out.println("The Current codeInstant Time Stamp is: "+codeInstant);
    }
}

Java’s use of the toInstant() method to get the current timestamp

Further, we can engage the toInstant() method of the Date class to acquire the current timestamp if we have a date object reflecting the timestamp.

import java.time.Instant;
import java.util.Date;

public class CodeToInstant {

    public static void main(String[] args) {

        Date codeDate = new Date();
        Instant codeInstant = codeDate.toInstant();
        System.out.println("The Current codeInstant Time Stamp is: "+codeInstant);
    }
}

Example: Java Get TimeStamp

import java.util.Date;
import java.sql.Timestamp;
 
public class CodeFetchTimeStamp
{
    public static void main( String[] args )
    {
 
 Date newDate= new Date();
 
 long timeNow = newDate.getTime();
     System.out.println("The Time now in Milliseconds: " + timeNow);
 
 Timestamp timestamp = new Timestamp(time);
 System.out.println("The Current Time Stamp is: " + timestamp);
    }
}

The getTime() function is used in the following example to obtain the current time in milliseconds. The timestamp will then convert to the correct time. The following example is multi-line. However, if you only want the current timestamp, use the one-line code above.

Example: Only get the date in Java

To find the date and time solely, use SimpleDateFormat with the Calendar class.

import java.util.Calendar;
import java.text.SimpleDateFormat;
 
public class CodeFetchTimeStamp
{
    public static void main( String[] args )
    {
         Calendar newCalendar = Calendar.getInstance();
 
         SimpleDateFormat sDateFormat = new SimpleDateFormat("MM/dd/yyyy");
         System.out.println(sDateFormat .format(newCalendar .getTime()));
    }
}

Example: Fetch The current Time in Java

You may also use SimpleDateFormat with the Calendar class to find the time only.

import java.util.Calendar;
import java.text.SimpleDateFormat;
 
public class CodeFetchTimeStamp
{
    public static void main( String[] args )
    {
         Calendar codeCalendar = Calendar.getInstance();
 
         SimpleDateFormat sDateFormat = new SimpleDateFormat("HH:mm:ss");
         System.out.println(sDateFormat .format(codeCalendar.getTime()));
    }
}

Example: Illustrating the use of Timestamp

// 2022-05-22 16:48:05.591
Timestamp new_timestamp = new Timestamp(System.currentTimeMillis());
System.out.println(new_timestamp)

  // 2022-05-22 16:48:05.591
  Date newDate = new Date();
Timestamp new_timestamp_two = new Timestamp(newDate.getTime());
System.out.println(new_timestamp_two)

  // convertion of an Instant to Timestamp
  Timestamp new_timestamp_three = Timestamp.from(Instant.now())
  System.out.println(new_timestamp_three)

  // convertion of a ZonedDateTime to Instant to Timestamp
  Timestamp new_timestamp_four = Timestamp.from(ZonedDateTime.now().toInstant()));
System.out.println(new_timestamp_four)

  // conversion of a Timestamp to Instant
  Instant instant = new_timestamp_four.toInstant();

Example: Java timestamps

The following software utilizes java.sql.Timestamp to acquire the current timestamp and SimpleDateFormat to format the display.

package com.codeunderscored;

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

public class CodeTimeStamp {

    // 2021.05.22.16.34.26
    private static final SimpleDateFormat simpleDateFormatOne = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
System.out.println(simpleDateFormatOne)

    // 2021-05-22T16:44:39.083+08:00
    private static final SimpleDateFormat simpleDateFormatTwo = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");

    // 2021-05-22 16:48:05
    private static final SimpleDateFormat simpleDateFormatThree = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) {

        // approach one
        Timestamp codeTimestamp = new Timestamp(System.currentTimeMillis());
        System.out.println(codeTimestamp);                      // 2021-05-22 16:34:26.666

        // approach two - via Date
        Date newDate = new Date();
        System.out.println(new Timestamp(newDate.getTime()));  // 2022-05-22 16:34:26.666
                                                            // The milliseconds count since January 1, 1970, 00:00:00 GMT
        System.out.println(codeTimestamp.getTime());            // 1616574866666

        System.out.println(simpleDateFormatOne.format(timestamp));         // 2022.05.22.16.34.26

        System.out.println(simpleDateFormatTwo.format(timestamp));         // 2022-05-22T16:48:05.591+08:00

        System.out.println(simpleDateFormatThree.format(timestamp));         // 2022-05-22 16:48:05

    }
}

Example: Instant to or from the Timestamp Converter

This example demonstrates how to use the new Java 8 java.time class. To and from the legacy java.sql.Timestamp is instant.

 // conversion of the Instant to an equivalent Timestamp
  Timestamp codeTimestamp = Timestamp.from(Instant.now())

  // converting a Timestamp to a corresponding Instant
  Instant instant = codeTimestamp.toInstant();

package com.codeunderscored;

import java.sql.Timestamp;
import java.time.Instant;

public class CodeInstant {

  public static void main(String[] args) {

      Timestamp codeTimestamp = new Timestamp(System.currentTimeMillis());
      System.out.println(codeTimestamp);                  // 2022-05-22 17:12:03.311
      System.out.println(codeTimestamp.getTime());        // 1616577123311

      // Converting a Timestamp to an Instant
      Instant newInstant = codeTimestamp.toInstant();
      System.out.println(newInstant);                    // 2022-05-22T09:12:03.311Z
      System.out.println(newInstant.toEpochMilli());     // 1616577123311

      // Conversion of an Instant to a corresponding Timestamp
      Timestamp timestampFromInstant = Timestamp.from(instant);
      System.out.println(timestampFromInstant.getTime());    // 1616577123311
  }
}

Example: Create a table with a timestamp

In JDBC programming, the timestamp is still extensively utilized. Consider the following conversions:

  // Java 8, java.time.*

  // converting a LocalDateTime to respective Timestamp
  preparedStatement.setTimestamp(1, Timestamp.valueOf(LocalDateTime.now()));

  // converting an Instant to a Timestamp
  preparedStatement.setTimestamp(1, Timestamp.from(Instant.now()));

  // Converting a ZonedDateTime to a corresponding Instant then to a  Timestamp
  preparedStatement.setTimestamp(3, Timestamp.from(ZonedDateTime.now().toInstant()));


The subsequent SQL example shows how to insert a Timestamp into a table using JDBC.

package com.codeunderscored;

import java.math.BigDecimal;
import java.sql.*;
import java.time.LocalDateTime;

public class CodeJdbc {

  private static final String sql_query = "INSERT into Code_Employee (name, emp_no, date_created) VALUES (?,?,?)";

  public static void main(String[] args) {

      try (Connection codeConnection = DriverManager.getConnection(
              "jdbc:postgresql://127.0.0.1:5432/code", "code", "Underscored");
           PreparedStatement codePrStatement = codeConnection.prepareStatement(sql_query)) {

          codePrStatement.setString(1, "Joy");
          codePrStatement.setBigDecimal(2, new BigDecimal("098"));
          codePrStatement.setTimestamp(3, Timestamp.valueOf(LocalDateTime.now()));

	// other alternatives for the date_created value
          // codePrStatement.setTimestamp(3, Timestamp.from(ZonedDateTime.now().toInstant()));
          // codePrStatement.setTimestamp(3, Timestamp.from(Instant.now()));

          int codeRow = codePrStatement.executeUpdate();

          // The count of rows affected
          System.out.println(codeRow); //1

      } catch (SQLException e) {
          System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
      } catch (Exception e) {
          e.printStackTrace();
      }

  }
}

Example: How to get the current timestamp in java

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

public class CodeTimeStamp
{
    public static void main( String[] args )
    {
         // Creating a Date object
	 Date codeDate= new Date();

         //getTime() returns current time in milliseconds
	 long codeTime = codeDate.getTime();

         // the count milliseconds is passed to constructor of Timestamp class
	 Timestamp codeTimestamp = new Timestamp(time);
	 System.out.println("The Current Time Stamp is: "+codeTimestamp);
    }
}

The actions we took in the example above are as follows:

1) Created a Date class object.

2) Using the getTime() method of Date, we obtained the current time in milliseconds.

3) Created a Timtestamp class object and supplied the milliseconds obtained in step 2 to the class’s constructor during object construction. The latter creates the timestamp from the millisecond value provided.

Conclusion

This lesson has shown you how to retrieve the current timestamp in Java and includes some sample code to help you grasp the concept. The Timestamp class, Date class, ZonedDateTime class, LocalDateTime class, and other Java classes can all be used to get the current timestamp.

The timestamp represents the date and time of an occurrence. Now’s timestamp is the current timestamp. The Java package’s Instant class, java.time.*, should be utilized for timestamp work. Also, note that the timestamp class has two important methods: now() and toString ().

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *