我使用的日期格式为:yyyy-mm-dd。
如何将此日期增加一天?
我使用的日期格式为:yyyy-mm-dd。
如何将此日期增加一天?
当前回答
我认为最快的一个,永远不会被弃用,它是一个深入核心的
let d=new Date();
d.setTime(d.getTime()+86400000);
console.log(d);
只有一行, 只有两个命令。 它工作在日期类型,不使用日历。
我一直认为最好在代码端使用unix时间,并在准备好显示给用户时显示日期。
要打印日期d,我使用
let format1 = new Intl.DateTimeFormat('en', { year: 'numeric', month: 'numeric', month: '2-digit', day: '2-digit'});
let [{ value: month },,{ value: day },,{ value: year }] = format1.formatToParts(d);
它可以设置月、年和日,但可以扩展到小时、分钟和秒,也可以根据国家国旗在标准表示中使用。
其他回答
java.time
在Java 8及以后的版本中,Java。时间包让这个过程变得很自动。(教程)
假设字符串输入和输出:
import java.time.LocalDate;
public class DateIncrementer {
static public String addOneDay(String date) {
return LocalDate.parse(date).plusDays(1).toString();
}
}
我更喜欢使用Apache的DateUtils。查看这个http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/time/DateUtils.html。它很方便,特别是当你必须在你的项目中多个地方使用它,而不想为此编写你的一行方法时。
API说:
addDays(Date Date, int amount):在返回新对象的日期上添加天数。
注意,它返回一个新的Date对象,并没有对前一个对象本身进行更改。
在Java 8中简单的方法是:
Date.from(Instant.now().plusSeconds(SECONDS_PER_DAY))
如果您正在使用Java 8,那么就像这样做。
LocalDate sourceDate = LocalDate.of(2017, Month.MAY, 27); // Source Date
LocalDate destDate = sourceDate.plusDays(1); // Adding a day to source date.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // Setting date format
String destDate = destDate.format(formatter)); // End date
如果您想使用SimpleDateFormat,那么就像这样做。
String sourceDate = "2017-05-27"; // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.setTime(sdf.parse(sourceDate)); // parsed date and setting to calendar
calendar.add(Calendar.DATE, 1); // number of days to add
String destDate = sdf.format(calendar.getTime()); // End date
自Java 1.5以来,TimeUnit.DAYS.toMillis(1)对我来说看起来更干净。
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
Date day = dateFormat.parse(string);
// add the day
Date dayAfter = new Date(day.getTime() + TimeUnit.DAYS.toMillis(1));