Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Working with System Time and Custom Formatting in Java

Tech May 9 57

Manipulating system time and specifying its output format in Java is efficient handled using the java.time API. The LocalDateTime class represents date and time with out a timezone, while DateTimeFormatter controls the display pattern.

To capture the current moment and format it, use LocalDateTime.now() and a formatter.

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

public class SystemTimeFormatter {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedNow = now.format(pattern);
        System.out.println(formattedNow);
    }
}

This code prints the current time in a year-month-day hour:minute:second layout.

You can also calculate past or future times. To get a date two days prior to the current date:

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

public class PastTimeCalculation {
    public static void main(String[] args) {
        LocalDateTime current = LocalDateTime.now();
        LocalDateTime twoDaysAgo = current.minusDays(2);

        DateTimeFormatter myFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String result = twoDaysAgo.format(myFormat);
        System.out.println(result);
    }
}

The minusDays(int) method subtracts the specified number of days. Similar methods like minusHours(int), minusMinutes(long), and minusSeconds(long) are available for other time units.

Customize the format string passed to DateTimeFormatter.ofPattern() to meet specific requiremants. Common pattern letters include yyyy for year, MM for month, dd for day, HH for 24-hour clock hour, mm for minute, and ss for second.

Tags: Java

Related Articles

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...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Comprehensive Guide to Hive SQL Syntax and Operations

This article provides a detailed walkthrough of Hive SQL, categorizing its features and syntax for practical use. Hive SQL is segmented into the following categories: DDL Statements: Operations on...

Leave a Comment

Anonymous

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