Sam Maul
Sam Maul

Reputation: 23

How to add 'T' to UTC timestamp without T and also add 5 mins to it

I wan to convert the string d (date in UTC format) to String in UTC format with 'T' and increment 5 mins to time. Below is the code

    public static void main (String args[]) throws ParseException
{
    String d="2021-08-27 06:25:00.716241+00:00";
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSSXXX");
    SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Date actualDate = format.parse(d);  
    String a=format1.format(actualDate);
    System.out.println(a);
}

I get output as 2021-08-27T12:06:56 but I need String 'a' as 2021-08-27T06:25:00 and then add 5 mins to it and make it 2021-08-27T06:30:00 Please help

Upvotes: 2

Views: 296

Answers (1)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79085

java.time

The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.

Solution using java.time, the modern Date-Time API:

import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        String d = "2021-08-27 06:25:00.716241+00:00";
        DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("u-M-d H:m:s.SSSSSSXXX", Locale.ENGLISH);
        OffsetDateTime odt = OffsetDateTime.parse(d, dtfInput);

        DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
        String str = odt.format(dtfOutput);
        System.out.println(str);

        // Add 5 minutes to it
        odt = odt.plusMinutes(5);
        str = odt.format(dtfOutput);
        System.out.println(str);
    }
}

Output:

2021-08-27T06:25:00
2021-08-27T06:30:00

ONLINE DEMO

Learn more about the modern Date-Time API* from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Upvotes: 6

Related Questions