Home > other >  I want to mark the date, but I don't know what to do
I want to mark the date, but I don't know what to do

Time:12-02

I have date this

regdate = 2021-12-02 11:30:05

I wanted to add 2 hours, so I added this code.

                val simpleDate = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH)
                val cal = Calendar.getInstance()
                cal.time = simpleDate.parse(regdate)
                cal.add(Calendar.HOUR, 2)

But the output value comes out like this and I'm going to ask a question.

13:30:05 

I want this time to this format

2021-12-02 13:30:05

How can I do this?

Thx for your help

CodePudding user response:

Looks like this is what you want

val simpleDate = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH)
val cal = Calendar.getInstance()
cal.time = simpleDate.parse("2021-12-02 11:30:05")
cal.add(Calendar.HOUR, 2)
println("0000000000000 =>"   simpleDate.format(cal.time))

=>> output: I/System.out: 0000000000000 =>2021-12-02 13:30:05

CodePudding user response:

java.time

Consider using java.time, the modern Java date and time API, for your date and time work.

With java.time one would usually declare the formatter a static constant. Excuse my Java syntax.

private static final DateTimeFormatter FORMATTER 
        = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss", Locale.ENGLISH);

Then the work goes like this:

    String regDateTimeString = "2021-12-02 11:30:05";

    ZoneId defaultZone = ZoneId.systemDefault();
    ZonedDateTime reg = LocalDateTime.parse(regDateTimeString, FORMATTER)
            .atZone(defaultZone);
    ZonedDateTime zdt = reg.plusHours(2);

    String output = zdt.format(FORMATTER);
    System.out.println(output);

Output in most time zones will be what you also expected:

2021-12-02 13:30:05

One thing I like about the java.time code is that it’s explicit that the calculation is dependent on time zone.

Tutorial link

Trail: Date Time (The Java™ Tutorials)

  • Related