当前位置: 首页 > 知识库问答 >
问题:

日期函数的Java[重复]

左丘峰
2023-03-14

谁能帮我写一下给任何日期增加天数的代码..?

例如,今天是2014年4月11日。我要2014年15-04 3天输出:2014年18-04。

我的问题不是将日期添加到当前日期…

共有3个答案

单于钊
2023-03-14
import java.util.Calendar;
import java.text.SimpleDateFormat;

public class A {
    public static void main(String[] args) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");

        Calendar calendar = Calendar.getInstance();    
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.MONTH, 1);
        calendar.set(Calendar.YEAR, 2012);
        calendar.add(Calendar.DAY_OF_MONTH, 3);

        System.out.println(simpleDateFormat.format(calendar.getTime()));
    }
}
公沈浪
2023-03-14
String dateString = "11-04-2014" // Say you have a date in String format
SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy"); // Create an instance of SimpleDateFormat with the right format.
Date date = format.parse(dateString); // Then parse the string, this will need a try catch statement.
Calendar calendar = Calendar.getInstance(); // Get an instance of the calendar.
calendar.setTime(date); // Set the time of the calendar to the parsed date
calendar.add(Calendar.DATE, 3); // Add the days to the calendar
String outputFormat = format.format(calendar.getTime());
呼延晋
2023-03-14

使用Java8,您可以编写:

import java.time.LocalDate;

LocalDate date = LocalDate.of(2014, 4, 11);
LocalDate newDate = date.plusDays(3);
System.out.println(newDate); //  Prints 2014-04-14

就这么简单。

 类似资料:
  • 问题内容: 您好,我试图在我创建的类的java中获取当前日期,但是一切都失败了。我已经在许多站点(例如http://www.mkyong.com/java/java- date-and-calendar-examples/)中 看到,日期构造函数没有参数,例如 现在在我的项目中,我尝试像这样使用它,但出现错误 构造函数Date()未定义 这怎么可能?到目前为止,我已经为您提供了完整的代码 我在Ec

  • 下表列出了XQuery提供的常用日期函数。 序号 函数 描述 1 current-date() 返回当前日期。 2 current-time() 返回当前时间。 3 current-dateTime() 返回当前日期和当前时间。

  • 我在尝试将java.util.Date转换为java.sql.Date时遇到了一些问题。传入的date参数最初是以下格式的字符串:2019-01-31。然后我尝试使用以下代码将其转换为java.util.date: 在我的SQL语句中,我试图将其转换为java。sql。日期: 然而,当我以字符串形式打印出缓冲区时,我意识到日期已更改。例如,我传入的数据字符串是2018-01-01,但在SQL语句中

  • 主要内容:GETDATE (),DATEPART(),DATEADD(),DATEDIFF(),CONVERT ()在 T-SQL 中,日期函数用于生成日期和时间的查询。 GETDATE () GETDATE()返回当前日期和时间。 GETDATE ()函数的语法 — 示例 该查询将返回 T-SQL 中的当前日期。 DATEPART() 它给出了日期或时间的一部分。 DATEPART()函数的语法 - 示例 该查询在 T-SQL 中返回当月的一部分。 DATEADD() 它通过减去或加上日期和时

  • 此页面列出了最常用的SQL Server日期函数,它们能够有效地处理日期和时间日期。 返回日期和时间函数 编号 函数 描述说明 1 DATENAME 以字符串形式返回日期部分 2 DATEPART 以整数形式返回日期部分 3 DAY 以整数形式返回指定日期 4 MONTH 以整数形式返回指定日期的月份 5 YEAR 以整数形式返回日期的年份。 返回两个日期之间的差值 编号 函数 描述说明 1 DA

  • 在 Lua 中,函数 time、date 和 difftime 提供了所有的日期和时间功能。 在 OpenResty 的世界里,不推荐使用这里的标准时间函数,因为这些函数通常会引发不止一个昂贵的系统调用,同时无法为 LuaJIT JIT 编译,对性能造成较大影响。推荐使用 ngx_lua 模块提供的带缓存的时间接口,如 ngx.today, ngx.time, ngx.utctime, ngx.l