取得下一天和上一天的日期

来源:互联网 发布:农村淘宝前景怎么样 编辑:程序博客网 时间:2024/06/02 11:11

package com.yqcf.util;

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

public class DateUtil {
 private static final DateUtil instance = new DateUtil();

 private DateUtil() {
 }

 public static DateUtil getInstance() {
  return instance;
 }

 /**
  *
  * 产生下一天的时间
  * @param dateTime:时间字符串(如20070101)
  * @return String(下一天的时间 如20070102)
  */
 public String nextDay(String dateTime) {
  Calendar now = Calendar.getInstance();
  // **************格式化时间的格式*******************//
  SimpleDateFormat simpledate = new SimpleDateFormat("yyyyMMdd");
  Date date = null;
  try {
   date = simpledate.parse(dateTime);
  } catch (ParseException ex) {
   System.out.println("日期格式不符合要求:" + ex.getMessage());
   return null;
  }
  // ****************设置下一天的时间*****************//
  now.setTime(date);
  int year = now.get(Calendar.YEAR);
  int month = now.get(Calendar.MONTH);
  int day = now.get(Calendar.DAY_OF_MONTH) + 1;
  now.set(year, month, day);
  String time = simpledate.format(now.getTime());
  return time;
 }

 /**
  *
  * 产生上一天的时间
  * @param dateTime:时间字符串(如20070101)
  * @return String(上一天的时间 如20061231)
  */
 public String previousDay(String dateTime) {
  Calendar now = Calendar.getInstance();
  // **************格式化时间的格式*******************//
  SimpleDateFormat simpledate = new SimpleDateFormat("yyyyMMdd");
  Date date = null;
  try {
   date = simpledate.parse(dateTime);
  } catch (ParseException ex) {
   System.out.println("日期格式不符合要求:" + ex.getMessage());
   return null;
  }
  // ****************设置下一天的时间*****************//
  now.setTime(date);
  int year = now.get(Calendar.YEAR);
  int month = now.get(Calendar.MONTH);
  int day = now.get(Calendar.DAY_OF_MONTH) - 1;
  now.set(year, month, day);
  String time = simpledate.format(now.getTime());
  return time;
 }