萍聚社区-德国热线-德国实用信息网

 找回密码
 注册

微信登录

微信扫一扫,快速登录

萍聚头条

查看: 614|回复: 0

1-1-8-13 请问一个关于时间的简单问题——

[复制链接]
发表于 2003-2-6 17:24 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?注册 微信登录

x

  1. 发信人: ioly (anguls), 信区: Java      
  2. 标  题: Re: ——请问一个关于时间的简单问题——
  3. 发信站: BBS 水木清华站 (Tue Oct 15 18:08:14 2002), 站内信件

  4. 但愿这个类能终结这类问题:)
  5. 暴力时间分析
  6. /**
  7. * SimpleTime是基于Calendar的一个简单的日期util.
  8. * 主要用途在于Calendar, Date和String间的转换.
  9. * 域只有年, 月, 日, 时, 分, 秒
  10. * 方法SimpleTime.create(String src, String format)可以识别所有形如
  11. * "yyyy-mm-dd","yy-mm-dd","hh:mi", "hh24:mi:ss", "yyyy/mm/dd hh24_mi_ss", "
  12. mi_ss_hh dd_yy_mm"等
  13. * 格式的format, 要求是年月日时分秒之间以任意多个非数字字符或者空格分隔
  14. * 程序将根据所给的format分析src, 返回一个SimpleTime类, 如果非法则返回null.
  15. * 两位年份表示法中00-09代表2002-2009, 10-99代表1910-1999
  16. * 方法SimpleTime.toString(String format)返回任意指定格式的日期String.
  17. * 需要注意的是jdk中1月为int 0, 12月为int 11
  18. */
  19. import java.util.Calendar;
  20. import java.util.Date;
  21. public class SimpleTime{
  22. private int year = 0;
  23. private int month = 0;
  24. private int day = 0;
  25. private int hour = 0;
  26. private int minute = 0;
  27. private int second = 0;
  28.     //数据缓冲
  29.     private Calendar calendar = Calendar.getInstance();
  30.     private Date date = new Date();
  31. /**
  32.   * default constructor, using current time
  33.   * @see setTime(Date c), setTime(Calendar c), SimpleTime.create(String src,
  34. String format)
  35.   */
  36. public SimpleTime(){
  37.   this.setTime(calendar);
  38. }
  39. /**
  40.   * constructor
  41.   */
  42. public SimpleTime(int year, int month, int day, int hour, int minute, int s
  43. econd){
  44.   this.year = year;
  45.   this.month = month;
  46.   this.day = day;
  47.   this.hour = hour;
  48.   this.minute = minute;
  49.   this.second = second;
  50. }
  51. /**
  52.   * constructor
  53.   */
  54. public SimpleTime(int year, int month, int day){
  55.   this.year = year;
  56.   this.month = month;
  57.   this.day = day;
  58. }
  59. /**
  60.   * constructor
  61.   * @param d
  62.   */
  63. public SimpleTime(SimpleTime st){
  64.   this.year = st.getYear();
  65.   this.month = st.getMonth();
  66.   this.day = st.getDay();
  67.   this.hour = st.getHour();
  68.   this.minute = st.getMinute();
  69.   this.second = st.getSecond();
  70. }
  71. /**
  72.   * constructor
  73.   */
  74. public SimpleTime(Date d){
  75.      this.setTime(d);
  76. }
  77. /**
  78.   * constructor
  79.   */
  80. public SimpleTime(Calendar c){
  81.      this.setTime(c);
  82. }
  83. /**
  84.   * get a clone
  85.   * @return new SimpleTime object
  86.   * @see SimpleTime(SimpleTime st)
  87.   */
  88. public SimpleTime getClone(){
  89.   return new SimpleTime(this);
  90. }
  91. /**
  92.   * 构造一个SimpleTime对象
  93.   * @param src 指明时间
  94.   * @param format 指明时间格式, 年月日时分秒之间必须有任意非数字分隔字符
  95.   * @return SimpleTime if successfully parsed and null if failed
  96.   */
  97. public static SimpleTime create(String src, String format){
  98.         SimpleTime st = new SimpleTime();
  99.         try{
  100.             char[] a = src.trim().toLowerCase().toCharArray();
  101.             char[] b = format.trim().toLowerCase().toCharArray();
  102.             int i0 = 0, i1 = 0, j0 = 0;
  103.             while(true){
  104.                 i0 = i1;
  105.                 while(i0 < a.length && !Character.isDigit(a[i0])){
  106.                     i0++;j0++;
  107.                 }
  108.                 if (i0 == a.length){
  109.                     break;
  110.                 }
  111.                 i1 = i0 + 1;
  112.                 while(i1 < a.length && Character.isDigit(a[i1])){
  113.                     i1++;
  114.                 }
  115.                 int val = Integer.parseInt(new String(a, i0, i1 - i0));
  116.                 if (b[j0] == 'y'){
  117.                     if (i1 - i0 == 4){//yyyy
  118.                         j0 = j0 + 4;
  119.                     }else{//yy
  120.                         j0 = j0 + 2;
  121.                         if (val < 10){
  122.        val += 2000;
  123.       }else val += 1900;
  124.                     }
  125.                     st.year = val;
  126.                 }else if (b[j0] == 'm'){
  127.                     if (b[j0 + 1] == 'm'){//mm
  128.                         st.month = val;
  129.                     }else{//mi
  130.                         st.minute = val;
  131.                     }
  132.                     j0 = j0 + 2;
  133.                 }else if (b[j0] == 'd'){//dd
  134.                     st.day = val;
  135.                     j0 = j0 + 2;
  136.                 }else if (b[j0] == 'h'){
  137.                     if ((j0 + 3 < b.length) && b[j0 + 2] == '2' && b[j0 + 3]
  138. == '4'){//hh24
  139.                         j0 = j0 + 4;
  140.                     }else{//hh
  141.                         j0 = j0 + 2;
  142.                     }
  143.                     st.hour = val;
  144.                 }else if (b[j0] == 's'){//ss
  145.                     st.second = val;
  146.                     j0 = j0 + 2;
  147.                 }
  148.             }
  149.             return st;
  150.         }catch(Exception e){
  151.             return null;
  152.         }
  153. }
  154. /**
  155.   * getter
  156.   */
  157. public int getYear(){
  158.   return year;
  159. }
  160. /**
  161.   * setter
  162.   */
  163. public void setYear(int year){
  164.   this.year = year;
  165. }
  166. /**
  167.   * getter
  168.   */
  169. public int getMonth(){
  170.   return month;
  171. }
  172. /**
  173.   * setter
  174.   */
  175. public void setMonth(int month){
  176.   this.month = month;
  177. }
  178. /**
  179.   * getter
  180.   */
  181. public int getDay(){
  182.   return day;
  183. }
  184. /**
  185.   * setter
  186.   */
  187. public void setDay(int day){
  188.   this.day = day;
  189. }
  190. /**
  191.   * getter
  192.   */
  193. public int getMinute(){
  194.   return minute;
  195. }
  196. /**
  197.   * setter
  198.   */
  199. public void setMinute(int minute){
  200.   this.minute = minute;
  201. }
  202. /**
  203.   * getter
  204.   */
  205. public int getHour(){
  206.   return hour;
  207. }
  208. /**
  209.   * setter
  210.   */
  211. public void setHour(int hour){
  212.   this.hour = hour;
  213. }
  214. /**
  215.   * getter
  216.   */
  217. public int getSecond(){
  218.   return second;
  219. }
  220. /**
  221.   * setter
  222.   */
  223. public void setSecond(int second){
  224.   this.second = second;
  225. }
  226. /**
  227.   * set the SimpleTime's time to the given Date object
  228.   * jdk中1月为int 0, 12月为int 11
  229.   * @param d a Date object
  230.   * @see setTime(Calendar c)
  231.   */
  232. public void setTime(Date d){
  233.   calendar.setTime(d);
  234.         this.setTime(calendar);
  235. }
  236.     /**
  237.      * set the SimpleTime's time to the given time
  238.      * from January 1, 1970, 00:00:00 GMT
  239.      * @param time
  240.      */
  241.     public void setTime(long time){
  242.         date.setTime(time);
  243.   this.setTime(date);
  244.     }
  245. /**
  246.   * set the SimpleTime's time to the given Calendar object<br>
  247.   * jdk中1月为int 0, 12月为int 11
  248.   * @param c a Calendar object
  249.   * @see Calendar.getInstance(), setTime(Date d)
  250.   */
  251. public void setTime(Calendar c){
  252.      year = c.get(Calendar.YEAR);
  253.      month = c.get(Calendar.MONTH) + 1;
  254.      day = c.get(Calendar.DAY_OF_MONTH);
  255.      hour = c.get(Calendar.HOUR_OF_DAY);
  256.      minute = c.get(Calendar.MINUTE);
  257.      second = c.get(Calendar.SECOND);
  258. }
  259. /**
  260.   * jdk中1月为int 0, 12月为int 11<br>
  261.   * Careful, this method won't test the validation of this SimpleTime<br>and
  262. you can always get a Date object
  263.   * @return a Date object using this SimpleTime's info
  264.   */
  265. public Date toDate(){
  266.      calendar.set(year, month - 1, day, hour, minute, second);
  267.            return calendar.getTime();
  268. }
  269. /**
  270.   * jdk中1月为int 0, 12月为int 11<br>
  271.   * Careful, this method won't test the validation of this SimpleTime<br>and
  272. you can always get a Calendar object
  273.   * @return a Calendar object using this SimpleTime's info
  274.   */
  275. public Calendar toCalendar(){
  276.      Calendar c = Calendar.getInstance();
  277.      c.set(year, month - 1, day, hour, minute, second);
  278.      return c;
  279. }
  280. /**
  281.   * calculator
  282.   * @param field "year" or "month" or "day" or "hour" or "minute" or "second
  283. "
  284.   * @param amount positive(+) for adding and negative(-) for subtraction
  285.   */
  286. public void add(String field, int amount){
  287.      calendar.set(year, month - 1, day, hour, minute, second);
  288.      if ("year".equalsIgnoreCase(field)){
  289.      calendar.add(Calendar.YEAR, amount);
  290.      }else if ("month".equalsIgnoreCase(field)){
  291.      calendar.add(Calendar.MONTH, amount);
  292.      }else if ("day".equalsIgnoreCase(field)){
  293.      calendar.add(Calendar.DAY_OF_MONTH, amount);
  294.      }else if ("hour".equalsIgnoreCase(field)){
  295.      calendar.add(Calendar.HOUR, amount);
  296.      }else if ("minute".equalsIgnoreCase(field)){
  297.      calendar.add(Calendar.MINUTE, amount);
  298.      }else if ("second".equalsIgnoreCase(field)){
  299.      calendar.add(Calendar.SECOND, amount);
  300.      }
  301.      this.setTime(calendar);
  302. }
  303. /**
  304.   * comparator
  305.   * @param s SimpleTime object
  306.   * @return true if this SimpleTime's time is after the given SimpleTime s a
  307. nd false if not
  308.   */
  309. public boolean after(SimpleTime s){
  310.   int yy = s.getYear();
  311.   int mm = s.getMonth();
  312.   int dd = s.getDay();
  313.   int hh = s.getHour();
  314.   int mi = s.getMinute();
  315.   int ss = s.getSecond();
  316.   return (year > yy
  317.     || year == yy && month > mm
  318.     || year == yy && month == mm && day > dd
  319.     || year == yy && month == mm && day == dd && hour > hh
  320.     || year == yy && month == mm && day == dd && hour == hh && minute > mi
  321.     || year == yy && month == mm && day == dd && hour == hh && minute == mi
  322. && second > ss
  323.     );
  324. }
  325. /**
  326.   * comparator
  327.   * @param s SimpleTime object
  328.   * @return true if this SimpleTime's time equals the given SimpleTime s and
  329. false if not
  330.   */
  331. public boolean equals(Object o){
  332.   if (o == null || !(o instanceof SimpleTime)){
  333.    return false;
  334.   }
  335.   SimpleTime s = (SimpleTime)o;
  336.   return (year == s.getYear()
  337.     && month == s.getMonth()
  338.     && day == s.getDay()
  339.     && hour == s.getHour()
  340.     && minute == s.getMinute()
  341.     && second == s.getSecond()
  342.     );
  343. }
  344. /**
  345.   * comparator
  346.   * @param s SimpleTime object
  347.   * @return true if this SimpleTime's time is before the given SimpleTime s
  348. and false if not
  349.   */
  350. public boolean before(SimpleTime s){
  351.   return !(after(s) || equals(s));
  352. }
  353. /**
  354.   * test whether current SimpleTime's year is a peak year<br>
  355.   * a peak year has 366 days
  356.   * @return true if this SimpleTime's year is a peak year and false if not
  357.   */
  358. public boolean isPeakYear(){
  359.   return (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0));
  360. }
  361. /**
  362.   * test whether this SimpleTime is a valid time
  363.   */
  364. public boolean isValid(){
  365.   if (month <= 0
  366.    || month > 12
  367.    || day <= 0
  368.    || day > 31
  369.    || hour < 0
  370.    || hour > 23
  371.    || minute < 0
  372.    || minute > 59
  373.    || second < 0
  374.    || second > 59)
  375.    return false;
  376.   switch (month){
  377.    case 2:{
  378.       if (isPeakYear()){
  379.        if (day > 29) return false;
  380.       }else if (day > 28) return false;
  381.       break;
  382.      }
  383.    case 4:
  384.    case 6:
  385.    case 9:
  386.    case 11:if (day > 30) return false;break;
  387.   }
  388.   return true;
  389. }
  390. /**
  391.   * try to create a SimpleTime using given src and format and test whether i
  392. t is valid
  393.   * @param src the time String
  394.   * @param format the format String
  395.   * @return true if a SimpleTime object created and this object is valid
  396.   *         and false if parse failed
  397.   * @see SimpleTime.create(String src, String format)
  398.   */
  399. public static boolean isValid(String src, String format){
  400.   boolean result = false;
  401.   SimpleTime s = SimpleTime.create(src, format);
  402.   if (s != null){
  403.    result = s.isValid();
  404.   }
  405.   return result;
  406. }
  407. /**
  408.   * get a "yyyy-mm-dd" String
  409.   * @return a String presents current SimpleTime
  410.   */
  411. public String toYMD(){
  412.      return year + "-"
  413.        + (month < 10?"0" + month:String.valueOf(month)) + "-"
  414.        + (day < 10?"0" + day:String.valueOf(day));
  415. }
  416. /**
  417.   * get a String presents current SimpleTime
  418.   * @param formatString a String points out the format<br>
  419.   * formatString can contain any of
  420.   * "yyyy", "yy", "mm", "dd", "hh24", "hh", "mi", "ss"
  421.   * for any times
  422.   * @return a String presents current SimpleTime
  423.   */
  424. public String toString(String formatString){
  425.   String format = formatString.trim().toLowerCase();
  426.   String[] accept = {"yyyy", "yy", "mm", "dd", "hh24", "hh", "mi", "ss"};
  427.   String[] data = {
  428.    String.valueOf(year),                                           //yyyy
  429.             year > 99?String.valueOf(year).substring(2):String.valueOf(year)
  430. ,//yy
  431.    month > 9?String.valueOf(month):"0" + month,                    //mm
  432.    day > 9?String.valueOf(day):"0" + day,                          //dd
  433.    hour > 9?String.valueOf(hour):"0" + hour,                       //hh24
  434.    (hour % 24) > 9?String.valueOf((hour % 24)):"0" + (hour % 24),  //hh
  435.    minute > 9?String.valueOf(minute):"0" + minute,                 //mi
  436.    second > 9?String.valueOf(second):"0" + second                  //ss
  437.   };
  438.   for(int i = 0, len = accept.length;i < len;i++){
  439.    format = SimpleTime.replace(format, accept[i], data[i]);
  440.   }
  441.   return format;
  442. }
  443. /**
  444.    * String replace like regex
  445.    * @param String str  string will replace
  446.    * @param String oldstr  will be replaced string
  447.    * @param String newstr  replace string
  448.    * @return String ret the string after replace
  449.    *
  450.    * @author Tony (tanxin@dichain.com)  2001-04-28
  451.    */
  452.    public static String replace(String str,String oldstr,String newstr){
  453.   int lastpos = -1;
  454.   String ret = "";
  455.   if (str == null || oldstr == null || newstr == null){
  456.     return str;
  457.   }
  458.   lastpos = str.indexOf(oldstr);
  459.   if (lastpos == -1){
  460.     return str;
  461.   }
  462.   while (lastpos >= 0){
  463.     ret = ret + str.substring(0,lastpos);
  464.     ret = ret + newstr;
  465.     str = str.substring(lastpos + oldstr.length());
  466.     lastpos = str.indexOf(oldstr);
  467.   }
  468.   if (str!=null && !str.trim().equals("")) ret = ret + str;
  469.   return ret;
  470.    }
  471.     /**
  472.      * get the day of the week, int 1 for sunday, 2 for Mon....
  473.      *
  474.      *
  475.      */
  476.     public int getDayOfWeek(){
  477.         calendar.set(year, month - 1, day, hour, minute, second);
  478.         return calendar.get(Calendar.DAY_OF_WEEK);
  479.     }
  480. /**
  481.   * for debug only
  482.   */
  483. public void show(){
  484.   System.out.println("\r\nyear==" + year
  485.          + " month==" + month
  486.          + " day==" + day
  487.          + " hour==" + hour
  488.          + " minute==" + minute
  489.          + " second==" + second
  490.          + " valid?==" + isValid()
  491.          + " yyyy-mm-dd==" + toYMD()
  492.          + " yyyy-mm-dd hh24:mi:ss==" + toString(" yyyy-mm-dd hh24:mi:ss")
  493.                            + " day_of_week==" + getDayOfWeek());
  494. }
  495. /**
  496.   * for test only
  497.   * @param args arguments
  498.   */
  499. public static void main(String[] args){
  500.         SimpleTime.create("8:00", "hh:mi").show();
  501.         SimpleTime st = SimpleTime.create("9:00", "hh:mi");
  502.         st.show();
  503.         st.add("hour", 1);
  504.         st.show();
  505.         st.add("month", 3);
  506.         st.show();
  507.         SimpleTime.create("2-3-4 2:3:4", "yyyy-mm-dd hh24:mi:ss").show();
  508. }
  509. }



  510. 【 在 qyjohn (Sweet Potato -- 太阳最红,咪咪最亲) 的大作中提到: 】
  511. : Press x on the article list,
  512. : x -> 3 -> 4 -> 8 -> 1
复制代码
Die von den Nutzern eingestellten Information und Meinungen sind nicht eigene Informationen und Meinungen der DOLC GmbH.
您需要登录后才可以回帖 登录 | 注册 微信登录

本版积分规则

手机版|Archiver|AGB|Impressum|Datenschutzerklärung|萍聚社区-德国热线-德国实用信息网 |网站地图

GMT+2, 2024-5-22 00:36 , Processed in 0.056735 second(s), 16 queries , MemCached On.

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表