|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?注册
x
- 发信人: ioly (anguls), 信区: Java
- 标 题: Re: ——请问一个关于时间的简单问题——
- 发信站: BBS 水木清华站 (Tue Oct 15 18:08:14 2002), 站内信件
- 但愿这个类能终结这类问题:)
- 暴力时间分析
- /**
- * SimpleTime是基于Calendar的一个简单的日期util.
- * 主要用途在于Calendar, Date和String间的转换.
- * 域只有年, 月, 日, 时, 分, 秒
- * 方法SimpleTime.create(String src, String format)可以识别所有形如
- * "yyyy-mm-dd","yy-mm-dd","hh:mi", "hh24:mi:ss", "yyyy/mm/dd hh24_mi_ss", "
- mi_ss_hh dd_yy_mm"等
- * 格式的format, 要求是年月日时分秒之间以任意多个非数字字符或者空格分隔
- * 程序将根据所给的format分析src, 返回一个SimpleTime类, 如果非法则返回null.
- * 两位年份表示法中00-09代表2002-2009, 10-99代表1910-1999
- * 方法SimpleTime.toString(String format)返回任意指定格式的日期String.
- * 需要注意的是jdk中1月为int 0, 12月为int 11
- */
- import java.util.Calendar;
- import java.util.Date;
- public class SimpleTime{
- private int year = 0;
- private int month = 0;
- private int day = 0;
- private int hour = 0;
- private int minute = 0;
- private int second = 0;
- //数据缓冲
- private Calendar calendar = Calendar.getInstance();
- private Date date = new Date();
- /**
- * default constructor, using current time
- * @see setTime(Date c), setTime(Calendar c), SimpleTime.create(String src,
- String format)
- */
- public SimpleTime(){
- this.setTime(calendar);
- }
- /**
- * constructor
- */
- public SimpleTime(int year, int month, int day, int hour, int minute, int s
- econd){
- this.year = year;
- this.month = month;
- this.day = day;
- this.hour = hour;
- this.minute = minute;
- this.second = second;
- }
- /**
- * constructor
- */
- public SimpleTime(int year, int month, int day){
- this.year = year;
- this.month = month;
- this.day = day;
- }
- /**
- * constructor
- * @param d
- */
- public SimpleTime(SimpleTime st){
- this.year = st.getYear();
- this.month = st.getMonth();
- this.day = st.getDay();
- this.hour = st.getHour();
- this.minute = st.getMinute();
- this.second = st.getSecond();
- }
- /**
- * constructor
- */
- public SimpleTime(Date d){
- this.setTime(d);
- }
- /**
- * constructor
- */
- public SimpleTime(Calendar c){
- this.setTime(c);
- }
- /**
- * get a clone
- * @return new SimpleTime object
- * @see SimpleTime(SimpleTime st)
- */
- public SimpleTime getClone(){
- return new SimpleTime(this);
- }
- /**
- * 构造一个SimpleTime对象
- * @param src 指明时间
- * @param format 指明时间格式, 年月日时分秒之间必须有任意非数字分隔字符
- * @return SimpleTime if successfully parsed and null if failed
- */
- public static SimpleTime create(String src, String format){
- SimpleTime st = new SimpleTime();
- try{
- char[] a = src.trim().toLowerCase().toCharArray();
- char[] b = format.trim().toLowerCase().toCharArray();
- int i0 = 0, i1 = 0, j0 = 0;
- while(true){
- i0 = i1;
- while(i0 < a.length && !Character.isDigit(a[i0])){
- i0++;j0++;
- }
- if (i0 == a.length){
- break;
- }
- i1 = i0 + 1;
- while(i1 < a.length && Character.isDigit(a[i1])){
- i1++;
- }
- int val = Integer.parseInt(new String(a, i0, i1 - i0));
- if (b[j0] == 'y'){
- if (i1 - i0 == 4){//yyyy
- j0 = j0 + 4;
- }else{//yy
- j0 = j0 + 2;
- if (val < 10){
- val += 2000;
- }else val += 1900;
- }
- st.year = val;
- }else if (b[j0] == 'm'){
- if (b[j0 + 1] == 'm'){//mm
- st.month = val;
- }else{//mi
- st.minute = val;
- }
- j0 = j0 + 2;
- }else if (b[j0] == 'd'){//dd
- st.day = val;
- j0 = j0 + 2;
- }else if (b[j0] == 'h'){
- if ((j0 + 3 < b.length) && b[j0 + 2] == '2' && b[j0 + 3]
- == '4'){//hh24
- j0 = j0 + 4;
- }else{//hh
- j0 = j0 + 2;
- }
- st.hour = val;
- }else if (b[j0] == 's'){//ss
- st.second = val;
- j0 = j0 + 2;
- }
- }
- return st;
- }catch(Exception e){
- return null;
- }
- }
- /**
- * getter
- */
- public int getYear(){
- return year;
- }
- /**
- * setter
- */
- public void setYear(int year){
- this.year = year;
- }
- /**
- * getter
- */
- public int getMonth(){
- return month;
- }
- /**
- * setter
- */
- public void setMonth(int month){
- this.month = month;
- }
- /**
- * getter
- */
- public int getDay(){
- return day;
- }
- /**
- * setter
- */
- public void setDay(int day){
- this.day = day;
- }
- /**
- * getter
- */
- public int getMinute(){
- return minute;
- }
- /**
- * setter
- */
- public void setMinute(int minute){
- this.minute = minute;
- }
- /**
- * getter
- */
- public int getHour(){
- return hour;
- }
- /**
- * setter
- */
- public void setHour(int hour){
- this.hour = hour;
- }
- /**
- * getter
- */
- public int getSecond(){
- return second;
- }
- /**
- * setter
- */
- public void setSecond(int second){
- this.second = second;
- }
- /**
- * set the SimpleTime's time to the given Date object
- * jdk中1月为int 0, 12月为int 11
- * @param d a Date object
- * @see setTime(Calendar c)
- */
- public void setTime(Date d){
- calendar.setTime(d);
- this.setTime(calendar);
- }
- /**
- * set the SimpleTime's time to the given time
- * from January 1, 1970, 00:00:00 GMT
- * @param time
- */
- public void setTime(long time){
- date.setTime(time);
- this.setTime(date);
- }
- /**
- * set the SimpleTime's time to the given Calendar object<br>
- * jdk中1月为int 0, 12月为int 11
- * @param c a Calendar object
- * @see Calendar.getInstance(), setTime(Date d)
- */
- public void setTime(Calendar c){
- year = c.get(Calendar.YEAR);
- month = c.get(Calendar.MONTH) + 1;
- day = c.get(Calendar.DAY_OF_MONTH);
- hour = c.get(Calendar.HOUR_OF_DAY);
- minute = c.get(Calendar.MINUTE);
- second = c.get(Calendar.SECOND);
- }
- /**
- * jdk中1月为int 0, 12月为int 11<br>
- * Careful, this method won't test the validation of this SimpleTime<br>and
- you can always get a Date object
- * @return a Date object using this SimpleTime's info
- */
- public Date toDate(){
- calendar.set(year, month - 1, day, hour, minute, second);
- return calendar.getTime();
- }
- /**
- * jdk中1月为int 0, 12月为int 11<br>
- * Careful, this method won't test the validation of this SimpleTime<br>and
- you can always get a Calendar object
- * @return a Calendar object using this SimpleTime's info
- */
- public Calendar toCalendar(){
- Calendar c = Calendar.getInstance();
- c.set(year, month - 1, day, hour, minute, second);
- return c;
- }
- /**
- * calculator
- * @param field "year" or "month" or "day" or "hour" or "minute" or "second
- "
- * @param amount positive(+) for adding and negative(-) for subtraction
- */
- public void add(String field, int amount){
- calendar.set(year, month - 1, day, hour, minute, second);
- if ("year".equalsIgnoreCase(field)){
- calendar.add(Calendar.YEAR, amount);
- }else if ("month".equalsIgnoreCase(field)){
- calendar.add(Calendar.MONTH, amount);
- }else if ("day".equalsIgnoreCase(field)){
- calendar.add(Calendar.DAY_OF_MONTH, amount);
- }else if ("hour".equalsIgnoreCase(field)){
- calendar.add(Calendar.HOUR, amount);
- }else if ("minute".equalsIgnoreCase(field)){
- calendar.add(Calendar.MINUTE, amount);
- }else if ("second".equalsIgnoreCase(field)){
- calendar.add(Calendar.SECOND, amount);
- }
- this.setTime(calendar);
- }
- /**
- * comparator
- * @param s SimpleTime object
- * @return true if this SimpleTime's time is after the given SimpleTime s a
- nd false if not
- */
- public boolean after(SimpleTime s){
- int yy = s.getYear();
- int mm = s.getMonth();
- int dd = s.getDay();
- int hh = s.getHour();
- int mi = s.getMinute();
- int ss = s.getSecond();
- return (year > yy
- || year == yy && month > mm
- || year == yy && month == mm && day > dd
- || year == yy && month == mm && day == dd && hour > hh
- || year == yy && month == mm && day == dd && hour == hh && minute > mi
- || year == yy && month == mm && day == dd && hour == hh && minute == mi
- && second > ss
- );
- }
- /**
- * comparator
- * @param s SimpleTime object
- * @return true if this SimpleTime's time equals the given SimpleTime s and
- false if not
- */
- public boolean equals(Object o){
- if (o == null || !(o instanceof SimpleTime)){
- return false;
- }
- SimpleTime s = (SimpleTime)o;
- return (year == s.getYear()
- && month == s.getMonth()
- && day == s.getDay()
- && hour == s.getHour()
- && minute == s.getMinute()
- && second == s.getSecond()
- );
- }
- /**
- * comparator
- * @param s SimpleTime object
- * @return true if this SimpleTime's time is before the given SimpleTime s
- and false if not
- */
- public boolean before(SimpleTime s){
- return !(after(s) || equals(s));
- }
- /**
- * test whether current SimpleTime's year is a peak year<br>
- * a peak year has 366 days
- * @return true if this SimpleTime's year is a peak year and false if not
- */
- public boolean isPeakYear(){
- return (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0));
- }
- /**
- * test whether this SimpleTime is a valid time
- */
- public boolean isValid(){
- if (month <= 0
- || month > 12
- || day <= 0
- || day > 31
- || hour < 0
- || hour > 23
- || minute < 0
- || minute > 59
- || second < 0
- || second > 59)
- return false;
- switch (month){
- case 2:{
- if (isPeakYear()){
- if (day > 29) return false;
- }else if (day > 28) return false;
- break;
- }
- case 4:
- case 6:
- case 9:
- case 11:if (day > 30) return false;break;
- }
- return true;
- }
- /**
- * try to create a SimpleTime using given src and format and test whether i
- t is valid
- * @param src the time String
- * @param format the format String
- * @return true if a SimpleTime object created and this object is valid
- * and false if parse failed
- * @see SimpleTime.create(String src, String format)
- */
- public static boolean isValid(String src, String format){
- boolean result = false;
- SimpleTime s = SimpleTime.create(src, format);
- if (s != null){
- result = s.isValid();
- }
- return result;
- }
- /**
- * get a "yyyy-mm-dd" String
- * @return a String presents current SimpleTime
- */
- public String toYMD(){
- return year + "-"
- + (month < 10?"0" + month:String.valueOf(month)) + "-"
- + (day < 10?"0" + day:String.valueOf(day));
- }
- /**
- * get a String presents current SimpleTime
- * @param formatString a String points out the format<br>
- * formatString can contain any of
- * "yyyy", "yy", "mm", "dd", "hh24", "hh", "mi", "ss"
- * for any times
- * @return a String presents current SimpleTime
- */
- public String toString(String formatString){
- String format = formatString.trim().toLowerCase();
- String[] accept = {"yyyy", "yy", "mm", "dd", "hh24", "hh", "mi", "ss"};
- String[] data = {
- String.valueOf(year), //yyyy
- year > 99?String.valueOf(year).substring(2):String.valueOf(year)
- ,//yy
- month > 9?String.valueOf(month):"0" + month, //mm
- day > 9?String.valueOf(day):"0" + day, //dd
- hour > 9?String.valueOf(hour):"0" + hour, //hh24
- (hour % 24) > 9?String.valueOf((hour % 24)):"0" + (hour % 24), //hh
- minute > 9?String.valueOf(minute):"0" + minute, //mi
- second > 9?String.valueOf(second):"0" + second //ss
- };
- for(int i = 0, len = accept.length;i < len;i++){
- format = SimpleTime.replace(format, accept[i], data[i]);
- }
- return format;
- }
- /**
- * String replace like regex
- * @param String str string will replace
- * @param String oldstr will be replaced string
- * @param String newstr replace string
- * @return String ret the string after replace
- *
- * @author Tony (tanxin@dichain.com) 2001-04-28
- */
- public static String replace(String str,String oldstr,String newstr){
- int lastpos = -1;
- String ret = "";
- if (str == null || oldstr == null || newstr == null){
- return str;
- }
- lastpos = str.indexOf(oldstr);
- if (lastpos == -1){
- return str;
- }
- while (lastpos >= 0){
- ret = ret + str.substring(0,lastpos);
- ret = ret + newstr;
- str = str.substring(lastpos + oldstr.length());
- lastpos = str.indexOf(oldstr);
- }
- if (str!=null && !str.trim().equals("")) ret = ret + str;
- return ret;
- }
- /**
- * get the day of the week, int 1 for sunday, 2 for Mon....
- *
- *
- */
- public int getDayOfWeek(){
- calendar.set(year, month - 1, day, hour, minute, second);
- return calendar.get(Calendar.DAY_OF_WEEK);
- }
- /**
- * for debug only
- */
- public void show(){
- System.out.println("\r\nyear==" + year
- + " month==" + month
- + " day==" + day
- + " hour==" + hour
- + " minute==" + minute
- + " second==" + second
- + " valid?==" + isValid()
- + " yyyy-mm-dd==" + toYMD()
- + " yyyy-mm-dd hh24:mi:ss==" + toString(" yyyy-mm-dd hh24:mi:ss")
- + " day_of_week==" + getDayOfWeek());
- }
- /**
- * for test only
- * @param args arguments
- */
- public static void main(String[] args){
- SimpleTime.create("8:00", "hh:mi").show();
- SimpleTime st = SimpleTime.create("9:00", "hh:mi");
- st.show();
- st.add("hour", 1);
- st.show();
- st.add("month", 3);
- st.show();
- SimpleTime.create("2-3-4 2:3:4", "yyyy-mm-dd hh24:mi:ss").show();
- }
- }
- 【 在 qyjohn (Sweet Potato -- 太阳最红,咪咪最亲) 的大作中提到: 】
- : Press x on the article list,
- : x -> 3 -> 4 -> 8 -> 1
复制代码 |
|