Java中为dd/MM/yyyy格式日期添加5天并保留原格式
问题
我有一个变量会生成格式为dd/MM/yyyy的随机日期,希望编写代码为该日期添加5天,示例如下:
05/12/2022 ---> 10/12/2022
我找到的代码如下:
String stringDate="05/12/2022"; Date date1=new SimpleDateFormat("dd/MM/yyyy").parse(stringDate); Calendar cal = Calendar.getInstance(); cal.setTime(date1); cal.add(Calendar.DATE, 5); Date dateWith5Days = cal.getTime(); System.out.println(dateWith5Days+" is the date after adding 5 days.");
这段代码的输出是:
Sat Dec 10 00:00:00 IST 2022 is the date after adding 5 days.
但我期望的输出是:
10/12/2022 is the date after adding 5 days.
请问如何修改代码以获得符合预期格式的结果?
解决方案
方法一:基于原有代码修改
你当前的问题是直接打印Date对象时,它会调用默认的toString()方法输出系统默认格式,而非你需要的dd/MM/yyyy。只需在输出时,再次使用SimpleDateFormat将处理后的Date对象格式化为指定格式即可。
修改后的代码:
String stringDate="05/12/2022"; SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); // 解析字符串为Date对象 Date date1 = sdf.parse(stringDate); Calendar cal = Calendar.getInstance(); cal.setTime(date1); cal.add(Calendar.DATE, 5); Date dateWith5Days = cal.getTime(); // 将处理后的Date对象格式化为指定字符串 String formattedDate = sdf.format(dateWith5Days); System.out.println(formattedDate + " is the date after adding 5 days.");
这段代码会输出你期望的10/12/2022 is the date after adding 5 days.。
方法二:使用Java 8+ 新日期API(推荐)
SimpleDateFormat和Calendar是Java早期的日期API,存在线程不安全、API设计繁琐等问题。Java 8及以后推荐使用java.time包下的新日期API,更简洁且安全。
示例代码:
import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class DateAddExample { public static void main(String[] args) { String stringDate = "05/12/2022"; // 定义日期格式器 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy"); // 解析字符串为LocalDate对象 LocalDate date = LocalDate.parse(stringDate, formatter); // 添加5天 LocalDate dateWith5Days = date.plusDays(5); // 格式化为指定字符串并输出 String formattedDate = dateWith5Days.format(formatter); System.out.println(formattedDate + " is the date after adding 5 days."); } }
这段代码同样能得到你想要的输出,且代码逻辑更清晰,无需处理冗余异常(若输入格式固定,可简化异常处理),同时线程安全。
内容的提问来源于stack exchange,提问作者Umar
相关产品推荐
相关产品推荐

