JAVA 非常实用的日期工具类

本文介绍了一个日期操作工具类,包括日期格式化、获取指定月份第一天、获取当前日期是一周中的哪一天等功能。提供了多种日期处理的方法,如默认格式化为“yyyy-MM-dd HH:mm:ss”等。

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

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtils extends org.apache.commons.lang.time.DateUtils {
	/**
	 * 格式化
	 *  
	 * @param date
	 * @param format
	 * @return String
	 */
	public static String parseDate(Date date, String parsePatterns) {
		SimpleDateFormat sdf = new SimpleDateFormat(parsePatterns);
		return sdf.format(date);
	}

	
	/**
	 * 默认格式化(yyyy-MM-dd HH:mm:ss)
	 * 
	 * @param date
	 * @return String
	 */
	public static String parseDate(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(date);
	}

	/**
	 * 默认格式化(yyyy-MM-dd HH:mm:ss)
	 * 
	 * @param str
	 * @return
	 * @throws ParseException
	 */
	public static Date parseDate(String str) throws ParseException {
		return DateUtils.parseDate(str, new String[] { "yyyy-MM-dd HH:mm:ss" });
	}

	/**
	 * 得到某个月的第一天
	 * 
	 * @param date
	 * @return Date
	 */
	public static Date getFirstDayOfMonth(Date date) throws ParseException {
		String strdate = DateUtils.parseDate(date, "yyyy-MM-01 00:00:00");
		return DateUtils.parseDate(strdate);
	}
	
	
	
	public static int getDayOfWeek() throws ParseException {
		Calendar c = Calendar.getInstance();
		int dayForWeek = 0;
		if(c.get(Calendar.DAY_OF_WEEK) == 1){ 
		   dayForWeek = 7; 
		}else{ 
		   dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1; 
		}
		return dayForWeek;
	}
	

	public static String getWeekOfDate(Date date,int tag) { 
	  String[] weekDaysName = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" }; 
	  String[] weekDaysCode = { "7", "1", "2", "3", "4", "5", "6" }; 
	  Calendar calendar = Calendar.getInstance(); 
	  calendar.setTime(date); 
	  int intWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1; 
	  if( tag == 0 ){
		  return weekDaysName[intWeek]; 
	  }else{
		  return weekDaysCode[intWeek]; 
	  }
	} 
	
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值