java获取当前日期的前一天日期与字符串日期之间的转换

本文深入探讨了Java中日期处理的相关技术,包括获取当前日期、时间戳转换以及字符串到日期的解析过程。通过实例演示,帮助开发者熟练掌握Java日期操作的技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这几天一直在处理Java的日期问题,通常需要按要求生成日期的话,通常会用到util包中的Calendar类,再用Calendar的getTime()方法生成对应的Date,最后用SimpleDateFormat输出。

 

1. 获取当期日期、年份、月份

import java.util.Calendar;


public class Main {
public static void main(String[] args) {
Calendar now = Calendar.getInstance();
System.out.println("Current Year is : " + now.get(Calendar.YEAR));
// month start from 0 to 11
System.out.println("Current Month is : " + (now.get(Calendar.MONTH) + 1));
System.out.println("Current Date is : " + now.get(Calendar.DATE));
}
}

 

2. 获取前一天、前一个月的日期

Calendar calendar = Calendar.getInstance();//此时打印它获取的是系统当前时间
calendar.add(Calendar.DATE, -1); //
得到前一天

String yestedayDate

= new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());


calendar.add(Calendar.MONTH, -1); //得到前一个月
int year = calendar.get(Calendar.YEAR);


int month = calendar.get(Calendar.MONTH)+1; //
输出前一月的时候要记得加1

 

3. 字符串转为日期格式

String date = "2010-02-01 23:59:59";

SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

try {

Date d = sf.parse(date);

System.out.println(sf.format(d));

} catch (ParseException e) {

e.printStackTrace();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值