2025-02-15

Java代碼

  1. 在 Java 應用中,格式化日期時間通常會用到 SimpleDateFormat 類   
  2. public class SimpleDateFormat extends DateFormat

      

  3. SimpleDateFormat 是一個以國別敏感的方式格式化和分析數據的具體類。 它允許格式
    化 (date -> text)、語法分析 (text -> date)和標準化。   
  4.   
  5. SimpleDateFormat 允
    許以為日期-時間格式化選擇任何用戶指定的方式啟動。 但是,希望
    用 DateFormat 中的 getTimeInstance、 getDateInstance 或 getDateTimeInstance 創
    建一個日期-時間格式化程序。 每個類方法返回一個以缺省格式化方式初始化的日期/時間格式化程序。 可以根據需要用 applyPattern 方法修
    改格式化方式。   
  6.   
  7. SimpleDateFormat
    函數的繼承關系:   
  8. java.lang.Object   
  9.     |
      
  10.      —-java.text.Format   
  11.             |
      
  12.              —-java.text.DateFormat   
  13.                     |
      
  14.                      —-java.text.SimpleDateFormat
      
  15. 下面是個小例子:   
  16. import java.text.*;

      

  17. import java.util.Date;

      

  18.   
  19. /**  
  20.    SimpleDateFormat
    函數語法:
     
  21.  
  22.    G 年代標志符  
  23.    y 年  
  24.    M 月  
  25.    d 日  
  26.    h 時 在上午或下
    午 (1~12)
     
  27.    H 時 在一天
    中 (0~23)
     
  28.    m 分  
  29.    s 秒  
  30.    S 毫秒  
  31.    E 星期  
  32.    D 一年中的第幾天  
  33.    F 一月中第幾個星期幾
     
  34.    w 一年中第幾個星期  
  35.    W 一月中第幾個星期  
  36.    a 上午 / 下午 標
    記符 
     
  37.    k 時 在一天
    中 (1~24)
     
  38.    K 時 在上午或下
    午 (0~11)
     
  39.    z 時區  
  40. */  
  41. public class FormatDateTime {

      

  42.   
  43.      public static void main(String[] args) {

      

  44.          SimpleDateFormat myFmt=new SimpleDateFormat(“yyyy年MM月dd日 HH時mm分ss秒”);

      

  45.          SimpleDateFormat myFmt1=new SimpleDateFormat(“yy/MM/dd HH:mm”); 

      

  46.          SimpleDateFormat myFmt2=new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);//等價於now.toLocaleString()   
  47.          SimpleDateFormat myFmt3=new SimpleDateFormat(“yyyy年MM月dd日 HH時mm分ss秒 E “);

      

  48.          SimpleDateFormat myFmt4=new SimpleDateFormat(

      

  49.                  “一年中的第 D 天 一年中第w個星期 一月中第W個星期 在一天中k時 z時區”);

      

  50.          Date now=new Date();   
  51.   &nbsp

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *