我有一个非常简单的问题,我不知道如何按 01/01/(用户年份)+1 扣除用户的日期。我真的陷入了这一点。
public static void main(String[] args)
{
String date;
Scanner teclado = new Scanner (System.in);
System.out.println("Dame una fecha formato dd/mm/yyyy");
date=teclado.next();
Date mydate =FinalAnio.ParseFecha(date);
System.out.println(mydate);
}
public static Date ParseFecha(String fecha)
{
SimpleDateFormat formato = new SimpleDateFormat("dd/mm/yyyy");
Date fechaDate = null;
try
{
fechaDate = formato.parse(fecha);
}
catch (ParseException ex)
{
System.out.println(ex);
}
return fechaDate;
}
最佳答案
java.util
的日期时间 API 及其格式化 APISimpleDateFormat
已过时且容易出错。建议完全停止使用并切换到 modern date-time API .- 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,则可以使用 ThreeTen-Backport它将大部分 java.time 功能向后移植到 Java 6 和 7。
- 如果您正在从事 Android 项目,并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaring和 How to use ThreeTenABP in Android Project .
请勿使用
mm
表示月份,因为它用于表示分钟。对于月份,正确的符号是MM
。检查DateTimeFormatter
了解有关用于解析/格式化字符串/日期时间的各种符号的更多信息。从Period and Duration了解周期和持续时间的计算 来自 Oracle 的教程。也值得浏览一下this Wikipedia page on Durations .
演示:
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Locale;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter date in the format dd/MM/yyyy: ");
String strDate = scanner.next();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/uuuu", Locale.ENGLISH);
LocalDate userDate = LocalDate.parse(strDate, dtf);
// The date representing 01/01/(the user year)+1
LocalDate targetDate = userDate.withDayOfMonth(1).withMonth(1).plusYears(1);
System.out.println("User's date: " + strDate);
System.out.println("Target date: " + targetDate.format(dtf));
Period period = Period.between(userDate, targetDate);
System.out.printf("Difference: %d days %d months %d years%n", period.getDays(), period.getMonths(),
period.getYears());
System.out.println("The difference in terms of days: " + ChronoUnit.DAYS.between(userDate, targetDate));
}
}
示例运行:
Enter date in the format dd/MM/yyyy: 20/10/2015
User's date: 20/10/2015
Target date: 01/01/2016
Difference: 12 days 2 months 0 years
The difference in terms of days: 73
从 Trail: Date Time 了解现代日期时间 API 。
关于date - 如何编写一个读取日期并计算距离年底还剩多少天的程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65114722/