how can I change only year in date String?

Viewed 324

I have java date string.

How can I change its year without changing the month and date.

e.g.

parts1[1]=   2020-1-2;
parts1[2]=   13:48:21;
CreatedDate = parts1[1]+" "+parts1[2];   
System.out.println(CreatedDate);

I want to change it to

parts1[1]=   2021-1-2;
parts1[2]=   13:48:21;
CreatedDate = parts1[1]+" "+parts1[2];   
System.out.println(CreatedDate);

I basically want to change the year without changing month and date

Can it be done?

2 Answers

java.time

You do not have to split the string and then combine the parts. You can parse the whole string into LocalDateTime and then use LocalDateTime#withYear to get a new instance with the specified year.

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

public class Main {
    public static void main(String[] args) {
        String creationDateTime = "2020-1-2 13:48:21";
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-M-d H:m:s", Locale.ENGLISH);
        LocalDateTime ldt = LocalDateTime.parse(creationDateTime, dtf);
        System.out.println(ldt);
        ldt = ldt.withYear(2021);

        // Default format
        String updatedDateTime = ldt.toString();
        System.out.println(updatedDateTime);

        // Custom format
        updatedDateTime = ldt.format(dtf);
        System.out.println(updatedDateTime);
    }
}

Output:

2020-01-02T13:48:21
2021-01-02T13:48:21
2021-1-2 13:48:21

Learn more about java.time API from Trail: Date Time.

try:

String[] arrOfStr = parts1[1].split("-", 2); 

arrOfStr[0] contains the year

Now you need to parse it as an int (since it's only 4 digits)

int year = Integer.parseInt(arrOfStr[0]);  

year now contains the the number 2020.

you can do

year++;

to increase it's value by 1

and to put it back in String format do:

arrOfStr[0] = "" + year;

or

arrOfStr[0] = String.valueOf(year);

to put it all together do this

parts1[1]= arrOfStr[0] + "-" arrOfStr[1]; //  2021-1-2

finally it should look like this:

parts1[1]=   2020-1-2;
parts1[2]=   13:48:21;

String[] arrOfStr = parts1[1].split("-", 2); 
int year = Integer.parseInt(arrOfStr[0]);  
year++;
arrOfStr[0] = "" + year;
parts1[1]= arrOfStr[0] + "-" + arrOfStr[1];


CreatedDate = parts1[1]+" "+parts1[2];   
System.out.println(CreatedDate);
Related