简体   繁体   中英

How to get the next date using java with present date as input

For my need, I have to update the date to the next day given I have the current date

The method I am using to get the current date


       SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT-4:00"));
        return sdf.format(new Date());

Now I want to get the next date using this as input I tried this

  System.out.println(Integer.parseInt(getOrderDate())+1);

I am getting this error

java.lang.NumberFormatException: For input string: "2020-01-06T09:46:29-0400

Can someone help and let me know.

The date-time API of java.util 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 .

If you are getting an object of java.util.Date , convert it into java.time.Instant and then get the OffsetDateTime from it by applying the required zone-offset. Finally, use OffsetDateTime#plusDays to get another instance with the required number of days added to it.

Demo:

import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Calendar;
import java.util.Date;

public class Main {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(202, 0, 6, 9, 46, 29);
        System.out.println(getNextDate(calendar.getTime()));
    }

    public static OffsetDateTime getNextDate(Date date) {
        return date.toInstant().atOffset(ZoneOffset.of("-04:00")).plusDays(1);
    }
}

Output:

0202-01-07T05:46:29.946-04:00

Learn about the modern date-time API from Trail: Date Time .

You have to add the day where you set the date:

 return sdf.format(new Date());

To do so, you can have a method like:

public String getOrderDate(Integer daysToAdd) {
    // Date computation
    Calendar c = Calendar.getInstance();
    c.setTime(new Date());
    if(daysToAdd!=null) {
       c.add(Calendar.DATE, daysToAdd);
    }
    // Date formatting
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
    sdf.setTimeZone(TimeZone.getTimeZone("GMT-4:00"));
    return sdf.format(c.getTime());
}

First, if you work with java 8 or higher I would strongly advise not to use outdated class java.util.Date and switch to package java.time . You can use class ZonedDateTime or any of its "brothers" such as LocalDateTime or others. Also with this package you can use class DateTimeFormatter to format your date to String. Also there it is easy to add or subtract number of any time units (such as days, minutes, months etc... by such methods as plusDays() .

However in your case you need to change the method getOrderDate to receive the date as parameter. You pass the date to your method and just convert it to String there. As for adding a day to your Date you can do it like this:

private static final Long ONE_DAY_IN_MILLISECONDS = 24L * 60L * 60L * 1000L 
Date date = new Date(); // current date
date.setTime(date.getTime() + ONE_DAY_IN_MILLISECONDS) // incrementing date by one day

First don't keep your order date in a string. Since you want the order time, keep it in an Instant . An Instant is a point in time independent of time zone or UTC offset (some say that it's in UTC). You can always format into a string in the user's time zone later when you need it for presentation. It's the same as numbers and Boolean values, you don't keep those in strings (I hope).

Second use java.time for your date and time work. The Instant class I mentioned belongs to java.time.

Third don't pretend that GMT-4:00 is a time zone. It's a GMT offset. Your users may use a different GMT offset about any time soon when summer time (DST) begins or ends or the politicians just change their minds about which GMT offset to belong to. Therefore use a proper time zone ID like America/Barbados. The format is region/city .

So your method gets simple:

public Instant getOrderDate() {
    return Instant.now();
}

To add a day — to get the same time tomorrow — you need first to decide on a time zone since in some time zones the day may be for example 23 or 25 hours long sometimes. I suppose you want to take this into account and not just blindly add 24 hours. So for example:

    ZoneId zone = ZoneId.of("Africa/Windhoek");
    ZonedDateTime orderDateTime = getOrderDate().atZone(zone);
    ZonedDateTime tomorrow = orderDateTime.plusDays(1);
    String tomorrowInIso8601Format = tomorrow.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
    System.out.println(tomorrowInIso8601Format);

Output when I ran just now:

2021-01-07T19:01:39.281591+02:00

I am exploiting the fact that the formatter is built in.

Link

Oracle tutorial: Date Time explaining how to use java.time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM