java操作时间用那个类好,JAVA实用日期时间操作类

在JAVA的使用过程中,经常要处理一些时间和日期,如果将其封装的话,可以方便以后使用。下面是我封装的一个简单的时间日期处理类,如果以后要有其他的扩展,下次再补充一下。

代码如下所示:

package cn.ac.iscas.gz.sems.domain.common.utils;

import java.text.DateFormat;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Calendar;

import java.util.Date;

public class DateUtils {

/**

* 以指定的格式来格式化日期

*

* @param date Date

* @param format String

* @return String

*/

public static String formatDateByFormat(java.util.Date date,String format)

{

String result = "";

if(date != null)

{

try

{

SimpleDateFormat sdf = new SimpleDateFormat(format);

result = sdf.format(date);

}

catch(Exception ex)

{

ex.printStackTrace();

}

}

return result;

}

/**

* 获取上个月字符串形式(yyyy-MM)

* @param currMonth

* @return

*/

public static String getLastMonth(String currMonth){

Date currDate = null;

String lastMonth = "";

DateFormat df2 = DateFormat.getDateInstance();

try {

currDate = df2.parse(currMonth);

Calendar calendar=Calendar.getInstance();

calendar.setTime(currDate);

calendar.add(Calendar.MONTH, -1);

SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM");

lastMonth = sdf.format(calendar.getTime());

} catch (ParseException e) {

lastMonth = "";

}

return lastMonth;

}

/**

* 获取上一天的日期

* 获取上个月字符串形式(yyyy-MM-dd)

* return prevDate

*/

public static String getPrevDate(String currDateStr){

Date currDate = null;

//上一个日期

String prevDate = "";

DateFormat df2 = DateFormat.getDateInstance();

try {

currDate = df2.parse(currDateStr);

Calendar calendar=Calendar.getInstance();

calendar.setTime(currDate);

//减去上一天的日期

calendar.add(Calendar.DATE, -1);

//格式化日期

SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");

prevDate = sdf.format(calendar.getTime());

} catch (ParseException e) {

prevDate = "";

}

return prevDate;

}

/**

* 得到当前系统的日期,时间格式为 yyyy-MM-dd

* @currStrDate

*/

public static String getLastDate(){

//得到当前系统日历

java.util.Calendar c=java.util.Calendar.getInstance();

//日期格式:yyyy年MM月dd日hh时mm分ss秒

java.text.SimpleDateFormat f=new java.text.SimpleDateFormat("yyyy-MM-dd");

//格式化该日期,得到字符串值

String currStrDate = f.format(c.getTime());

return currStrDate;

}

// public static void main(String[] args) {

System.out.println(getPrevDate("2012-6-1"));

// getLastDate();

//}

} *****

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值