JAVA的一些常用时间工具

JAVA常用的时间方法


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

/**
 * 时间相关类
 * 
 * @author Administrator
 *
 */
public class TimeUtil {

	/**
	 * 获取时间格式
	 * 
	 * @param format
	 *            需要的时间格式 常用格式例如:yyyy-MM-dd HH:mm:ss 、yyyy/MM/dd HH:mm:ss
	 * @return
	 */
	public String getNowTime(String format) {
		if (!"".equals(format) && format != null) {

			Date date = new Date();
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
			String time = simpleDateFormat.format(date);
			return time;
		} else {

			return "";
		}

	}

	/**
	 * 
	 * @param nowTime
	 *            新时间
	 * @param oldTime
	 *            旧时间
	 * @return 两个时间的相差秒数
	 */

	public static int getTimeDelta(String nowTime, String oldTime) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		Date date1;
		Date date2;
		try {
			date1 = format.parse(nowTime);
			date2 = format.parse(oldTime);
			long timeDelta = (date1.getTime() - date2.getTime()) / 1000;// 单位是秒
			int secondsDelta = (timeDelta < 0 ? (int) timeDelta : (int) Math.abs(timeDelta));
			return secondsDelta;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return 0;
		}

	}

	/**
	 * 获取格林时间
	 * 
	 * @return
	 */
	public static String getGreenTime() {
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("EEE d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
		sdf.setTimeZone(TimeZone.getTimeZone("GMT")); // 设置时区为GMT
		String str = sdf.format(calendar.getTime());
		return str;
	}

	/**
	 * 获取当月的第一天
	 * 
	 */
	public static String getfirstday() {
		Calendar cale =  Calendar.getInstance();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String firstday;
		// 获取前月的第一天
		cale = Calendar.getInstance();
		cale.add(Calendar.MONTH, 0);
		cale.set(Calendar.DAY_OF_MONTH, 1);
		firstday = format.format(cale.getTime());
		return firstday;
	}

	/**
	 * 获取当月的最后一天
	 * 
	 * @return 
	 */
	public static String getlastday() {
		Calendar cale = Calendar.getInstance();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String lastday;
		// 获取前月的最后一天
		cale = Calendar.getInstance();
		cale.add(Calendar.MONTH, 1);
		cale.set(Calendar.DAY_OF_MONTH, 0);
		lastday = format.format(cale.getTime());
		return lastday;
	}
	
	 
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值