开发学院软件开发Java MIDP中对日期时间的简单转换 阅读

MIDP中对日期时间的简单转换

 2007-12-23 12:37:55 来源:WEB开发网   
核心提示:MIDP的Date和Calendar类都是J2SE的精简版,也没有SimpleDateFormat之类的格式化类,MIDP中对日期时间的简单转换,因此,写了一个简单的DateTime类实现本地日期和时间的格式化,package com.crackj2ee.midp.util;import java.util.*;pub

MIDP的Date和Calendar类都是J2SE的精简版,也没有SimpleDateFormat之类的格式化类,因此,写了一个简单的DateTime类实现本地日期和时间的格式化。

package com.crackj2ee.midp.util;
import java.util.*;
public final class DateTime {
   PRivate static String[] WEEKDAYS = {"SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"};
   public final String timeZone;
   public final int year;
   public final int month;
   public final int day;
   public final int weekday;
   public final int hour;
   public final int minute;
   public final int second;
   public DateTime(Date date, String timeZone) {
     this.timeZone = timeZone;
     Calendar c = timeZone==null ? Calendar.getInstance() : Calendar.getInstance(TimeZone.getTimeZone(timeZone));
     c.setTime(date);
     year = c.get(Calendar.YEAR);
     month = c.get(Calendar.MONTH);
     day = c.get(Calendar.DAY_OF_MONTH);
     weekday = c.get(Calendar.DAY_OF_WEEK);
     hour = c.get(Calendar.HOUR_OF_DAY);
     minute = c.get(Calendar.MINUTE);
     second = c.get(Calendar.SECOND);
   }
   public DateTime(long time, String timeZone) {
     this(new Date(time), timeZone);
   }
   public Date toDate() {
     Calendar c = Calendar.getInstance(TimeZone.getTimeZone(timeZone));
     c.set(Calendar.YEAR, year);
     c.set(Calendar.MONTH, month);
     c.set(Calendar.DAY_OF_MONTH, day);
     c.set(Calendar.HOUR_OF_DAY, hour);
     c.set(Calendar.MINUTE, minute);
     c.set(Calendar.SECOND, second);
     return c.getTime();
   }
   public String toDateString() {
     return year + "-" + (month+1) + "-" + day + "(" + WEEKDAYS[weekday-1] + ")";
   }
   public String toTimeString() {
     return hour + ":" + minute + ":" + second;
   }
   public String toString() {
     return toDateString() + " " + toTimeString();
   }
}


示例:

输出当前日期和时间:new DateTime(new Date(), "GMT+8").toString();
转换到Date对象:toDate();

注意,要指定时区,否则时间永远是GMT标准时间。可以在Windows时区设置中查询,北京时间是"GMT+8"

(出处:http://www.cncms.com)


Tags:MIDP 日期 时间

编辑录入:爽爽 [复制链接] [打 印]
[]
  • 好
  • 好的评价 如果觉得好,就请您
      0%(0)
  • 差
  • 差的评价 如果觉得差,就请您
      0%(0)
赞助商链接