当前位置: 移动技术网 > IT编程>开发语言>Java > Java SimpleDateFormat中英文时间格式化转换详解

Java SimpleDateFormat中英文时间格式化转换详解

2019年07月19日  | 移动技术网IT编程  | 我要评论

simpledateformat是一个以与语言环境有关的方式来格式化和解析日期的具体类。它允许进行格式化(日期 -> 文本)、解析(文本 -> 日期)和规范化。

simpledateformat使得可以选择任何用户定义的日期-时间格式的模式。但是,仍然建议通过dateformat中的gettimeinstance、getdateinstance 或 getdatetimeinstance 来创建日期-时间格式器。每一个这样的类方法都能够返回一个以默认格式模式初始化的日期/时间格式器。可以根据需要使用applypattern 方法来修改格式模式。

日期和时间模式


simpledateformat使用方法

根据上面的的“日期和时间模式”,设定需要匹配的模式,可以实现string与date类型的互转,例如:

string类型的时间转换成date类型时间,比较常用的几种时间格式转换如下:

a. 时间格式: “2015-08-28”, 模式: “yyyy-mm-dd”

simpledateformat dateformat = new simpledateformat("yyyy-mm-dd");
date date = dateformat.parse("2015-08-28");

b. 时间格式: “2015-08-28 18:28:30”, 模式: “yyyy-mm-dd hh:mm:ss”

simpledateformat dateformat = new simpledateformat("yyyy-mm-dd hh:mm:ss");
date date = dateformat.parse("2015-08-28 18:28:30");

c. 时间格式: “2015-8-28”, 模式: “yyyy-m-d”

simpledateformat dateformat = new simpledateformat("yyyy-m-d");
date date = dateformat.parse("2015-8-28");

d. 时间格式: “2015-8-28 18:8:30”, 模式: “yyyy-m-d h:m:s”

simpledateformat dateformat = new simpledateformat("yyyy-m-d h:m:s");
date date = dateformat.parse("2015-8-28 18:8:30");

e. 时间格式: “aug 28, 2015 6:8:30 pm”, 模式: “mmm d, yyyy h:m:s aa”

simpledateformat dateformat = new simpledateformat("mmm d, yyyy h:m:s aa", locale.english);
date date = dateformat.parse("aug 28, 2015 6:8:30 pm");

f. 时间格式: “fri aug 28 18:08:30 cst 2015”, 模式: “eee mmm d hh:mm:ss ‘cst' yyyy”

simpledateformat dateformat = new simpledateformat("eee mmm d hh:mm:ss 'cst' yyyy", locale.english);
date date = dateformat.parse("fri aug 28 18:08:30 cst 2015");

date类型的时间转换成string类型时间

这是“string类型的时间转换成date类型时间”的逆向操作,只要将date date = dateformat.parse([string型时间]);换成string date = dateformat.format([date型时间]);即可。例如,将当前时间格式化成[yyyy年m月d日]的形式:

simpledateformat dateformat = new simpledateformat("yyyy年m月d日");
string date = dateformat.format(new date());

注:我们在做时间格式转换时,主要是找对匹配时间格式的模式;另外,英文格式的时间转换时需要带上locale.english,否则会转换失败,因为它默认的是本地化的设置,除非你的操作系统是英文的,总之时间转换时需要时间格式与模式保持一致。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网