mianyou556

有个功能,要获取当前时间以15分钟为间隔的集合数组,一开始用calendar.add(Calendar.MINUTE, -count);方法来获取当前时间前count分钟的时间,循环获取发现有问题,如:当前为10:02,第一次获取的时间为10:00是正确的,循环获取09:45的时间时,就不对了,目前不知道具体是什么原因造成的。现在采用了另外一个方法来获取,当前时间的毫秒数减去15分钟的毫秒数。不多说,看下面的代码:

package cn.sh.ideal.util;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class DateUtil {
 
 /**
  * 
  * @Title get15MinutesListByCurrentDate
  * @Description 获取长度为length的、时间间隔为15分钟的、长度为length的List集合
  * @param length
  * @return
  * @date Aug 17, 2012
  */
 public static List<String> get15MinutesListByCurrentDate(long length) {
  List<String> dateList = new ArrayList<String>();
  Calendar calendar = Calendar.getInstance();
  SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");//时间格式 
  int minute = calendar.get(Calendar.MINUTE);// 得到分钟
  int count = 0;
  if (minute != 0 && minute != 15 && minute != 30 && minute != 45) { //时间不为00,15,30,45的情况
   for (int i = minute; i >= 0; i--) { //判断距离最近的00,15,30,45的分钟数
    if (i % 15 == 0) {
     break;
    } else {
     count++;
    }
   }
  }
  calendar.add(Calendar.MINUTE, -count); //获取最近的分钟

  int year = calendar.get(Calendar.YEAR); //得到年
  int month = calendar.get(Calendar.MONTH) + 1; //得到月
  int day = calendar.get(Calendar.DAY_OF_MONTH);// 得到天
  int hour = calendar.get(Calendar.HOUR_OF_DAY);// 得到小时
  int mi = calendar.get(Calendar.MINUTE);// 得到分钟
  String date = "";
  if (month < 10) {
   date = year + "0" + month + "" + day + hour + "" + mi; //月分0-9,转换为0开头
  }
  if (mi == 0) {
   date = year + "0" + month + "" + day + hour + "" + mi + "0"; //分钟为00
  }
  date += "00"; //加秒
  try {
   long millionSeconds = sdf.parse(date).getTime(); // 时间转毫秒
   System.out.println(sdf.format(millionSeconds)); //毫秒转时间
   for (long i = 0; i < length; i++) {
    dateList.add(String.valueOf(millionSeconds - i
      * (15 * 60 * 1000)));
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  return dateList;
 }

 public static void main(String[] args) {
  DateUtil.get15MinutesListByCurrentDate(new Long(20));
 }
}

posted on 2012-08-17 23:06  mianyou556  阅读(1848)  评论(0编辑  收藏  举报

分类:

技术点:

相关文章:

  • 2021-10-12
  • 2021-12-18
  • 2021-12-18
  • 2022-12-23
  • 2021-11-09
  • 2021-12-18
猜你喜欢
  • 2021-12-28
  • 2021-12-18
  • 2021-07-26
  • 2021-12-28
  • 2022-02-28
相关资源
相似解决方案