Date and time in Java

@ (Date and time in Java)

Date and Time

The most commonly used several classes, Date, DateFormat, Calendar, Locale

Date

1. constructor with no arguments

//根据当前系统默认的毫秒值创建时间对象
    public Date() {
        this(System.currentTimeMillis());
    }

2. Create an object according to the time value in milliseconds

   long time = 1000*60*60;
   Date d = new Date(time);

3. Object creation time minutes and seconds passed date

Date d2 =  new Date(20,10,10,11,11,11)
//这得到的时间并不是20-10-10这种
//下面是源码
public Date(int year, int month, int date, int hrs, int min, int sec) {
     int y = year + 1900;
     // month is 0-based. So we have to normalize month to support Long.MAX_VALUE.
     if (month >= 12) {
         y += month / 12;
         month %= 12;
     } else if (month < 0) {
         y += CalendarUtils.floorDivide(month, 12);
         month = CalendarUtils.mod(month, 12);
     }
     BaseCalendar cal = getCalendarSystem(y);
     cdate = (BaseCalendar.Date) cal.newCalendarDate(TimeZone.getDefaultRef());
     cdate.setNormalizedDate(y, month + 1, date).setTimeOfDay(hrs, min, sec, 0);
     getTimeImpl();
     cdate = null;
 }

DateFormat

DateFormat is an abstract class subclasses the date and time format, which formats and parses the date and time to a language-independent manner.
He is an abstract class, using its subclass SimpleDateFormat

Internal DateFormat class itself provides for direct operation instantiated

//得到日期的DateFormat对象:
public static final DateFormat getDateInstance();

//得到日期时间的DateFormat对象:
public static final DateFormat getDateTimeInstance();

//使用DateFormat类格式化Date类日期
public final String format(Date date)

SimpleDateFormat class
inheritance SimpleDateFormat function:
java.lang.Object
|
+ - java.text.Format
   |
   + - java.text.DateFormat
      |
      + - java.text.SimpleDateFormat

//构造方法:
public SimpleDateFormat(String pattern)

//转换:
public Date parse(String source)throws ParseException //-->此时取得的是全部时间数。

//格式化:
public final String Format(Date date)   //-->将时间重新格式化成字符串显示。

Converted to the Date format specified date

public class FormatDateTime {
     public static void main(String[] args) {
         SimpleDateFormat myFmt=new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
         SimpleDateFormat myFmt1=new SimpleDateFormat("yy/MM/dd HH:mm"); 
         SimpleDateFormat myFmt2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//等价于now.toLocaleString()
         SimpleDateFormat myFmt3=new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒 E ");
         SimpleDateFormat myFmt4=new SimpleDateFormat("一年中的第 D 天 一年中第w个星期 一月中第W个星期 在一天中k时 z时区");
         Date now=new Date();
         System.out.println(myFmt.format(now));
         System.out.println(myFmt1.format(now));
         System.out.println(myFmt2.format(now));
         System.out.println(myFmt3.format(now));
         System.out.println(myFmt4.format(now));
         System.out.println(now.toGMTString());
         System.out.println(now.toLocaleString());
         System.out.println(now.toString());
     }    
}

The date given string extracted as Date

In doing so, usually a date string, but not the format you want, it can first be converted to Date, and then converted to other formats.

import java.text.* ;  
import java.util.* ;  
public class DateDemo05{  
    public static void main(String args[]){  
        String strDate = "2008-10-19 10:11:30.345" ;  
        // 准备第一个模板,从字符串中提取出日期数字  
        String pat1 = "yyyy-MM-dd HH:mm:ss.SSS" ;  
        // 准备第二个模板,将提取后的日期数字变为指定的格式  
        String pat2 = "yyyy年MM月dd日 HH时mm分ss秒SSS毫秒" ;  
        SimpleDateFormat sdf1 = new SimpleDateFormat(pat1) ;        // 实例化模板对象  
        SimpleDateFormat sdf2 = new SimpleDateFormat(pat2) ;        // 实例化模板对象  
        Date d = null ;  
        try{  
            d = sdf1.parse(strDate) ;   // 将给定的字符串中的日期提取出来  
        }catch(Exception e){            // 如果提供的字符串格式有错误,则进行异常处理  
            e.printStackTrace() ;       // 打印异常信息  
        }  
        System.out.println(sdf2.format(d)) ;    // 将日期变为新的格式  
    }  
};

DateFormat and SimpleDateFormat the difference

1.DateFormat can be used directly, but which itself is an abstract class, the corresponding date and time can be obtained according to the format specified region Locate

2.SimpleDateFormat class is a subclass of DateFormat class, in terms of general DateFormat class is rarely used directly. The use SimpleDateFormat class is completed.

1、DateFormat:是抽象类,所以使用子类SimpleDateFormat
 
2、SimpleDateFormat类构造方法:
    public SimpleDateFormat():使用默认模式。
    public SimpleDateFormat(String pattern):使用给定的模式。
        API规定的模式:y M d H m s
  
3、SimpleDateFormat类成员方法:
    public final String format(Date date):日期格式化为日期字符串。
    pattern Date parse(String source):日期字符串解析为日期。

Calendar

Calendar: It provides a conversion between a specific instant in a set, such as a calendar field YEAR, MONTH, DAY_OF_MONTH, HOUR some other method, and for manipulating the calendar fields (e.g., date of obtaining the next week) provides a number of methods.

First, the constructor
protected Calendar (): As the modifier is protected, it can not create the object directly. This object needs to be generated by other means.

Second, members of the method
members Calendar Method class
static Calendar getInstance ()

District and regional settings when using the default calendar get. Calendar object generated by this method. As follows:

Calendar cr=Calendar.getInstance();
public void set(int year,int month,int date,int hourofday,int minute,int second)    设置日历的年、月、日、时、分、秒。
public int get(int field)   返回给定日历字段的值。所谓字段就是年、月、日等等。
public void setTime(Date date)  使用给定的Date设置此日历的时间。Date------Calendar
public Date getTime()   返回一个Date表示此日历的时间。Calendar-----Date
abstract void add(int field,int amount) 按照日历的规则,给指定字段添加或减少时间量。
public long getTimeInMillies()  以毫秒为单位返回该日历的时间值。

Third, the Calendar field
Calendar field contains the following two ways: one is a unit of time, such as year, month, day, and so on. The other is the specific date, such as January, February and March, one day, two days, three days, one o'clock, two o'clock, and so specific time. The former is used when acquiring general, the latter is generally used when the determination.

Time unit field:

YEAR 年 MINUTE 分
DAY_OF_WEEK_IN_MONTH

The first few weeks of a month
MONTH, SECOND / MILLISECOND seconds / milliseconds WEEK_OF_MONTH type of calendar weeks
DATE day DAY_OF_MONTH
and DATE as

DAY_OF_YEAR on how many days a year
HOUR_OF_DAY when DAY_OF_WEEK few weeks how many weeks a year WEEK_OF_YEAR

AM_PM return a representation afternoon, returns 0 morning.

public class CalendarDemo {
    public static void main(String[] args) {
        // 其日历字段已由当前日期和时间初始化:
        Calendar rightNow = Calendar.getInstance(); // 子类对象
        // 获取年
        int year = rightNow.get(Calendar.YEAR);
        // 获取月
        int month = rightNow.get(Calendar.MONTH);
        // 获取日
        int date = rightNow.get(Calendar.DATE);
        //获取几点
        int hour=rightNow.get(Calendar.HOUR_OF_DAY);
        //获取上午下午
        int moa=rightNow.get(Calendar.AM_PM);
        if(moa==1)
            System.out.println("下午");
        else
            System.out.println("上午");
 
        System.out.println(year + "年" + (month + 1) + "月" + date + "日"+hour+"时");
        rightNow.add(Calendar.YEAR,5);
        rightNow.add(Calendar.DATE, -10);
        int year1 = rightNow.get(Calendar.YEAR);
        int date1 = rightNow.get(Calendar.DATE);
        System.out.println(year1 + "年" + (month + 1) + "月" + date1 + "日"+hour+"时");
    }
}

Note: month is starting from zero, but from the beginning of the month is, so need to add a month

Locale

Locale general for international, Locale represents a particular region, Locale class supports a lot of countries and regions. We can through the following methods to view the entire region Locale support:

Locale[] ls = Locale.getAvailableLocales();
for (Locale locale:ls) {
  System.out.println("locale :"+locale);
}

The main constructor

// Locale的构造函数
Locale(String language)
Locale(String language, String country)
Locale(String language, String country, String variant)

Use examples:
Here Insert Picture Description
the java internationalization, another article described.

Guess you like

Origin www.cnblogs.com/scholar-hwg/p/12060308.html