打印出今天的日期。这应该是MM / DD / YYYY的形式。月份应从1开始而不是0.提示读取要添加到当前日期的天数并打印新日期。
请任何人帮助我
import java.util.calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class JavaDateAdd {
public static void main(String[] args) {
Date date = new Date();
System.out.println("Today's Date Is: " + (now.get(Calendar.MONTH) + 1) + "/" + now.get(Calendar.DATE) + "/" + now.get(Calendar.YEAR));
System.out.print("Number of Days You Want To ADD: ");
int AddDays = in.nextInt();
Date newDate = addDays(date,AddDays);
System.out.println("Java Date after adding "+AddDays+" days: "+(now.get(Calendar.MONTH) + 1) + "/" + now.get(Calendar.DATE) + "/" + now.get(Calendar.YEAR));
}
}`
答案 0 :(得分:0)
使用SimpleDateFormat进行日期格式化: SimpleDateFormat是一个具体的类,用于以区域设置敏感的方式格式化和解析日期。 SimpleDateFormat允许您从为日期时间格式选择任何用户定义的模式开始。例如:
import java.util.*;
import java.text.*;
public class HelloWorld {
public static void main(String args[]) {
Date dNow = new Date( );
SimpleDateFormat sdf =
new SimpleDateFormat ("MM/dd/yyyy ");
System.out.println("Current Date: " + sdf.format(dNow));
Calendar c = Calendar.getInstance();
c.setTime(new Date()); // Now use today date.
c.add(Calendar.DATE, 35); // Adding 35 days
String output = sdf.format(c.getTime());
System.out.println("New Date: "+ output);
}
}
这会产生以下结果:
Current Date: 09/24/2015
New Date: 10/29/2015
答案 1 :(得分:0)
您可以修改代码以接受不占用天数并接受您的日期格式。
public static void main(String [] args){
Calendar cal = Calendar.getInstance();
// print current date
System.out.println("The current date is : " + cal.getTime());
// add 20 days to the calendar
cal.add(Calendar.DATE, 20);
System.out.println("20 days later: " + cal.getTime());
Date tommrrow = cal.getTime();
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yy");
String date = formatter.format(tommrrow);
System.out.println("20 days in dd-MM-yy: " + date);
}
答案 2 :(得分:0)
打印出今天的日期。这应该是MM / DD / YYYY的形式。月份应从1而不是0开始。
首先看一下DateTimeFormatter
,例如:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
System.out.println("Today is " + formatter.format(LocalDateTime.now()));
提示阅读要添加到当前日期的天数
首先查看Scanning,例如:
Scanner scanner = new Scanner(System.in);
System.out.print("How many days to add: ");
int days = scanner.nextInt();
并打印新日期。
首先查看Java 8's Date Time API,例如:
LocalDateTime ldt = LocalDateTime.now();
ldt = ldt.plusDays(days);
System.out.println(formatter.format(ldt));