Home > Back-end >  How to convert int days to timestamp format in java
How to convert int days to timestamp format in java

Time:06-08

I am getting the date in integer format which is like 4,5,10,31 etc.
I want to convert this into timestamp format for the same month/year like,

if today is 10th January, 2022 and I am getting 4 in my output, I want to convert this 4 to 4th January, 2022 but in timestamp format.

Need help in Java only, please.

CodePudding user response:

If you are only dealing with dates then you can use LocalDate or if you also need to consider times as well then go for LocalDateime. In any case, you will be able to set year, month, day, and times values as per your choice(setting time in Localdate is not needed unless you are parsing it to LocalDatetime).

You can use of() method from both LocalDate or LocalDateTime to set values and create an instance of them.

LocalDate date = LocalDate.of(year, month, dayOfMonth);
//or
LocalDateTime dateTime = LocalDateTime.of(year, month, dayOfMonth, hour, minute, second)

Also you can use withYear(),withMonth() etc methods to create a new LocalDate instance .

The withYear() method of the LocalDate class in Java returns a copy of this LocalDate with the year altered. All the other similar functions follow the same thing.Eg:-

LocalDate date = LocalDate.now(); //returns current default system time.
LocalDate date2 = date.withYear(2012)
                    .withMonth(1)
                    .withDayOfMonth(1);

//date2 will be '2012-01-01' while date will remain same i.e current time.

You can follow this tutorial for examples

CodePudding user response:

i want to convert this into timestamp format for the same month/year like if today is 10th january, 2022 and i am getting 4 in my output, i want to convert this 4 to 4th january, 2022 This should do it for you:

LocalDate firstDayOfThisMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
System.out.println(firstDayOfThisMonth.plusDays(7)); // 7 days after start of month
  • Related