Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Subtracting Two Minutes from a Timestamp in Java

Tech 1

Adjusting a Date Instance by Removing Two Minutes

Using the legacy java.util package, you can manipulate time values by converting a Date into a Calendar instance.

1. Initialize the Timestamp

Create a variable holding the current moment in time.

java.util.Date now = new java.util.Date();

2. Wrap with Calendar

Obtain a Calendar instance and assign the previously created Date to it. This allows for field-level manipulation.

java.util.Calendar timeWrapper = java.util.Calendar.getInstance();
timeWrapper.setTime(now);

3. Perform the Subtraction

Invoke the add method on the minute field. Passing a negative value decreases the time.

timeWrapper.add(java.util.Calendar.MINUTE, -2);

4. Retrieve the Result

Extract the modified time back into a Date object.

java.util.Date adjustedTime = timeWrapper.getTime();

Complete Implementation

import java.util.Calendar;
import java.util.Date;

public class TimeShifter {
    public static void main(String[] args) {
        Date initialStamp = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(initialStamp);
        cal.add(Calendar.MINUTE, -2);
        Date resultStamp = cal.getTime();

        System.out.println("Initial Timestamp: " + initialStamp);
        System.out.println("Timestamp Minus 2 Minutes: " + resultStamp);
    }
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.