how to change the current date

Viewed 221

my method accepts - hours, minutes, seconds and milliseconds separated by sign / as a string parameter how can I add to the current date the parameters that come to the method.

Example 1: today, 02/10/2021, the method receives metnode data (10/10/10/10) - output - 02/10/2021 10:10:10

Example 2: today, 02/10/2021, the method receives metnode data (55/10/10/10) - output - 02/12/2021 07:10:10 That is, you need to add 55 hours 10 seconds 10 seconds and 10 milliseconds to the current date.

you cannot use the Calendar and StringTokenizer classes.

public void method(String s) {

        s = s.replaceAll("/", "-");

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss");

        final LocalDateTime now = LocalDateTime.parse(s, formatter.withResolverStyle(ResolverStyle.LENIENT));

        System.out.println(now);
    }

i found the withResolverStyle (ResolverStyle.LENIENT) method but did not understand how to use it.

4 Answers

A lenient DateTimeFormatter is enough

I don’t know if it’s the best solution. That probably depends on taste. It does use the ResolverStyle.LENIENT that you mentioned and generally works along the lines of the code in your question, only fixed and slightly simplified.

My formatter includes both date and time. This is necessary for surplus hours to be converted to days.

private static final DateTimeFormatter formatter = new DateTimeFormatterBuilder()
        .appendPattern("uuuu-MM-dd H/m/s/")
        .appendValue(ChronoField.MILLI_OF_SECOND)
        .toFormatter()
        .withResolverStyle(ResolverStyle.LENIENT);

Next thing we need a string that matches the formatter. So let’s prepend the date to the time string that we already have got:

    String timeString = "55/10/10/10";
    
    LocalDate today = LocalDate.now(ZoneId.of("America/Regina"));
    String dateTimeString = "" + today + ' ' + timeString;
    LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);

    System.out.println(dateTime);

The output from my code when I ran it today (February 10) was:

2021-02-12T07:10:10.010

A different idea: use Duration

Edit: An alternative is to use the Duration class. A reason for doing that would be that it really appears that you are adding a duration rather than setting the time of day. A liability is that parsing your string into a Duration is a bit tricky. The Duration.parse method that we want to use only accepts ISO 8601 format. It goes like PT55H10M10.010S for a period of time of 55 hours 10 minutes 10.010 seconds. And yes, milliseconds need to be given as a fraction of the seconds.

    String isoTimeString = timeString.replaceFirst("(/)(\\d+)$", "$100$2")
            .replaceFirst("(\\d+)/(\\d+)/(\\d+)/0*(\\d{3})", "PT$1H$2M$3.$4S");
    Duration dur = Duration.parse(isoTimeString);
    LocalDateTime dateTime = LocalDate.now(ZoneId.of("Asia/Kathmandu"))
            .atStartOfDay()
            .plus(dur);

When I ran it just now — already February 11 in Kathmandu, Nepal — the output was:

2021-02-13T07:10:10.010

I am using two calls to replaceFirst(), each time using a regular expression. The first call simply adds some leading zeroes to the milliseconds. $1 and $2 in the replacement string give us what was matched by the first and the second group denoted with round brackets in the regular expression.

The second replaceFirst() call established the ISO 8601 format, which includes making sure that the milliseconds are exactly three digits so they work as a decimal fraction of the seconds.

Link: ISO 8601

just for simplicity , you can your LocalDateTime class. it is easy to understand. please refer to below code is used to add the hours, minuts, second and nanos to current Date Time. this Date Time then can easy formatted by any format pattern as required.

  public void addDateTime(int hours, int minuts, int seconds, int nanos) {
        LocalDateTime adt = LocalDateTime.now();
        System.out.println(adt);
        adt = adt.plusHours(hours);
        adt = adt.plusMinutes(minuts);
        adt = adt.plusSeconds(seconds);
        adt = adt.plusNanos(nanos);
        System.out.println(adt);
        
    }

Try this:

public void method(String s) {
    String[] arr = s.split("/");
    LocalDateTime now = LocalDateTime.of(
        LocalDate.now(), LocalTime.of(0, 0))
        .plusHours(Integer.parseInt(arr[0]))
        .plusMinutes(Integer.parseInt(arr[1]))
        .plusSeconds(Integer.parseInt(arr[2]))
        .plusNanos(Integer.parseInt(arr[3]) * 1_000_000L);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss");
    System.out.println(now.format(formatter));
}
Related