1. 编程学习网 > 编程教程 > java教程 > 第十四章-String类-3

第十四章-String类-3

DateFormat创建对象与不能直接使用new关键字来创建对象,而是使用getDateInstance()方法(DateFormat类中的一个静态方法)来创建对象。创建好的DateFormat对象也是调用对象中的方法来对日期时间进行格式化操作,其样式可以通过DateFormat常量控制。例程中就是通过DateFormat常量来控制其长度和语言的(长度有SHORT、MEDIUM、LONG、FULL四个量可设置)。
import java.util.*;
public class StringDemo{
    public static void main(String[] args){
        DateFormat object1=DateFormat.getDateInstance(DateFormat.SHORT,Locale.CHINA);
        DateFormat object2=DateFormat.getDateInstance(DateFormat.MEDIUM,Locale.CHINA);
        DateFormat object3=DateFormat.getDateInstance(DateFormat.LONG,Locale.CHINA);
        DateFormat object4=DateFormat.getDateInstance(DateFormat.FULL,Locale.CHINA);
        DateFormat object5=DateFormat.getDateInstance(DateFormat.FULL,Locale.ENGLISH);
        String str1=object1.format(new Date());
        String str2=object2.format(new Date());
        String str3=object3.format(new Date());
        String str4=object4.format(new Date());
        String str5=object5.format(new Date());
 
        System.out.println(str1);
        System.out.println(str2);
        System.out.println(str3);
        System.out.println(str4);
        System.out.println(str5);
    }
}

SimpleDateFormat类有三种构造方法,构造方法1是应用默认的格式与语言环境进行格式化,构造方法2是应用指定格式,但应用默认语言环境进行格式化。构造方法3则是应用指定的格式与语言环境进行格式化。
SimpleDateFormat();//构造方法1
SimpleDateFormat("yyyy-MM-dd");//构造方法2
SimpleDateFormat("yyyy-MM-dd",Locale.CHINA);//构造方法3
SimpleDateFormat需要先创建Date对象,其后再进行格式化。使用日期和时间格式化编码来确立格式化的格式。
import java.text.*;
import java.util.*;
public class StringDemo{
    public static void main(String[] args){
        Date object1=new Date();
 
        SimpleDateFormat one=new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat two=new SimpleDateFormat("yyyy-MM- dd",Locale.ENGLISH);
 
        System.out.println(one.format(object1));
        System.out.println(two.format(object1));
    }
}

(日期和时间格式化编码)

本文由IT教学网整理发布,转载请注明出处:http://www.itjx.com/jiaocheng/java/457.html

联系我们

在线咨询:点击这里给我发消息

咨询电话:400-998-2681

工作时间:7*24小时无休