Java 8有新的Date-Time API来处理日期和时间。 我们应该使用新的Java 8 Date-Time API来格式化和解析日期时间值。
如果我们正在编写与日期和时间相关的新代码,我们应该使用新的Date-Time API。
使用新的Java 8日期时间API格式化日期和时间。
此部分适用于使用旧日期和日历类的旧代码。
Java库提供了两个类来格式化日期:
- java.text.DateFormat
- java.text.SimpleDateFormat
类是一个抽象类并且我们可以使用类以预定义的格式来格式化日期。
因为它是抽象的,所以我们不能创建一个类的实例使用运算符。
我们必须使用它的一个方法来创建新的实例。Xxx可以是日期,日期时间或时间。
要格式化日期时间值,我们使用方法类。
DateFormat类的格式化文本取决于两件事:
- 样式
- 语言环境
格式的样式决定了包括多少日期时间信息在格式化的文本
语言环境确定要使用的语言环境。
类将五个样式定义为常量:
- DateFormat.DEFAULT
- DateFormat.SHORT
- DateFormat.MEDIUM
- DateFormat.LONG
- DateFormat.FULL
格式与相同。getInstance()使用。
下表显示了对于美国区域设置以不同样式格式化的相同日期。
以下代码显示如何以简体中文格式显示语言环境的默认日期,法国和德国。
import java.text.DateFormat; import java.util.Date; import java.util.Locale; public class Main { public static void main(String[] args) { Date today = new Date(); // Print date in the default locale format Locale defaultLocale = Locale.getDefault(); printLocaleDetails(defaultLocale); printDate(defaultLocale, today); // Print date in French format printLocaleDetails(Locale.FRANCE); printDate(Locale.FRANCE, today); // Print date in German format. We could also use Locale.GERMANY // instead of new Locale ("de", "DE"). Locale germanLocale = new Locale("de", "DE"); printLocaleDetails(germanLocale); printDate(germanLocale, today); } public static void printLocaleDetails(Locale locale) { String languageCode = locale.getLanguage(); String languageName = locale.getDisplayLanguage(); String countryCode = locale.getCountry(); String countryName = locale.getDisplayCountry(); // Print the locale info System.out.println("Language: " + languageName + "(" + languageCode + "); " + "Country: " + countryName + "(" + countryCode + ")"); } public static void printDate(Locale locale, Date date) { DateFormat formatter = DateFormat.getDateInstance(DateFormat.SHORT, locale); String formattedDate = formatter.format(date); System.out.println("SHORT: " + formattedDate); formatter = DateFormat.getDateInstance(DateFormat.MEDIUM, locale); formattedDate = formatter.format(date); System.out.println("MEDIUM: " + formattedDate+" "); } }
讯享网
上面的代码生成以下结果。
类包含常见语言环境的常量。
我们可以使用方法获取系统的默认区域设置。
要创建自定义日期格式,我们可以使用类。
SimpleDateFormat类是对语言环境敏感的。
它的默认构造函数创建一个格式化程序,默认日期格式为默认语言环境。
类中的方法执行日期格式。
要更改后续格式化的日期格式,可以通过将新日期格式作为参数传递来使用applyPattern()方法。
讯享网import java.text.SimpleDateFormat; import java.util.Date; public class Main { public static void main(String[] args) { SimpleDateFormat simpleFormatter = new SimpleDateFormat("dd/MM/yyyy"); Date today = new Date(); String formattedDate = simpleFormatter.format(today); System.out.println("Today is (dd/MM/yyyy): " + formattedDate); simpleFormatter.applyPattern("MMMM dd, yyyy"); formattedDate = simpleFormatter.format(today); System.out.println("Today is (MMMM dd, yyyy): " + formattedDate); } } 上面的代码生成以下结果。
SimpleDateFormat日期和时间格式由日期和时间模式字符串指定。
在格式字符串中,从“A"到“Z"和从“a"到“z"被视为表示日期或时间字符串的组成部分的格式字母。
文本可以使用单引号(“)引用,以避免解释。“"表示单引号。 所有其他字符不解释并且将被简单地复制到输出字符串中。
定义了以下模式字母:
下表有一些示例格式字符串及其结果。
我们可以将字面量嵌入格式化的日期。
我们需要将它们放在单引号中以将它们作为文字。
import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class Main { public static void main(String[] args) { GregorianCalendar gc = new GregorianCalendar(2010, Calendar.SEPTEMBER,9); Date birthDate = gc.getTime(); String pattern = ""I was born on the day" dd "of the month "MMMM "in" yyyy"; SimpleDateFormat simpleFormatter = new SimpleDateFormat(pattern); System.out.println(simpleFormatter.format(birthDate)); } } 上面的代码生成以下结果。
我们可以使用parse()方法将String值转换为日期时间值类。
parse()方法的签名如下:
讯享网public Date parse(String text, ParsePosition startPos)
parse()方法接受两个参数。text是要解析的字符串,startPos设置文本中字符从您要开始解析的位置开始的位置。
以下代码显示如何将字符串解析为日期值。
import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Date; public class Main { public static void main(String[] args) { String text = "09/19/2014"; // Create a pattern for the date text "09/19/2014" String pattern = "MM/dd/yyyy"; SimpleDateFormat simpleFormatter = new SimpleDateFormat(pattern); // a ParsePosition object with value zero ParsePosition startPos = new ParsePosition(0); // Parse the text Date parsedDate = simpleFormatter.parse(text, startPos); System.out.println(parsedDate); } } 上面的代码生成以下结果。
以下代码解析单个字符串中的两个日期值。
讯享网import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Date; public class Main { public static void main(String[] args) { String text = "ab01/01/1999cd12/31/2000ef"; String pattern = "MM/dd/yyyy"; SimpleDateFormat simpleFormatter = new SimpleDateFormat(pattern); // Set the start index at 2 ParsePosition startPos = new ParsePosition(2); // Parse the text to get the first date (January 1, 1999) Date firstDate = simpleFormatter.parse(text, startPos); System.out.println(firstDate); //Now, startPos has its index set after the last character of the first date parsed. int currentIndex = startPos.getIndex(); System.out.println(currentIndex); // To set its index to the next date increment its index by 2. int nextIndex = currentIndex + 2; startPos.setIndex (nextIndex); // Parse the text to get the second date (December 31, 2000) Date secondDate = simpleFormatter.parse(text, startPos); System.out.println(secondDate); } } 上面的代码生成以下结果。
以下代码显示如何解析时间戳以获取时间零件
import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class Main { public static void main(String[] args) { String input = "2014-05-04 09:10:40.321"; // Prepare the pattern String pattern = "yyyy-MM-dd HH:mm:ss.SSS"; SimpleDateFormat sdf = new SimpleDateFormat(pattern); // Parse the text into a Date object Date dt = sdf.parse(input, new ParsePosition(0)); System.out.println(dt); // Get the Calendar instance Calendar cal = Calendar.getInstance(); cal.setTime(dt); // Print time parts System.out.println("Hour:" + cal.get(Calendar.HOUR)); System.out.println("Minute:" + cal.get(Calendar.MINUTE)); System.out.println("Second:" + cal.get(Calendar.SECOND)); System.out.println("Millisecond:" + cal.get(Calendar.MILLISECOND)); } } 上面的代码生成以下结果。
以下两个类可用于格式化和解析数字:
- java.text.NumberFormat
- java.text.DecimalFormat
类可以格式化一个数字特定地区的预定义格式。
类可以格式化数字以特定区域设置的自定义格式。
NumberFormat类的方法返回格式化程序对象的实例。
XXX可以由数字,货币,整数或百分比替换,或只是getInstance()。这些方法都是重载的。
如果你调用它们没有参数,它们返回一个格式化对象默认语言环境。
使用number参数调用format()方法以将格式化的数字作为字符串。
讯享网import java.text.NumberFormat; public class Main { public static void main(String[] args) { NumberFormat formatter; // Get number formatter for default locale formatter = NumberFormat.getInstance(); System.out.println(formatter.format(12312.)); } } 上面的代码生成以下结果。
下面的代码说明了如何以默认格式为当前语言环境,法语语言环境和德语语言环境格式化数字。
import java.text.NumberFormat; import java.util.Locale; public class Main { public static void main(String[] args) { double value = .; // Default locale printFormatted(Locale.getDefault(), value); // Indian locale Locale indianLocale = new Locale("en", "IN"); printFormatted(indianLocale, value); } public static void printFormatted(Locale locale, double value) { // Get number and currency formatter NumberFormat nf = NumberFormat.getInstance(locale); NumberFormat cf = NumberFormat.getCurrencyInstance(locale); System.out.println("Format value: " + value + " for locale: " + locale); System.out.println("Number: " + nf.format(value)); System.out.println("Currency: " + cf.format(value)); } } 上面的代码生成以下结果。
要执行更高级的格式化,我们可以使用DecimalFormat类。
DecimalFormat类允许我们提供我们自己的格式模式。 的下表显示模式及其用法。
一旦我们创建了DecimalFormat类的对象,就可以改变格式模式使用其方法。
讯享网import java.text.DecimalFormat; public class Main { private static DecimalFormat formatter = new DecimalFormat(); public static void main(String[] args) { formatNumber(".", 12.345); formatNumber(".", 12.345); formatNumber("0000.0000", 12.345); formatNumber("#.", -12.345); // Positive and negative number format formatNumber("#.;(#.)", -12.735); } public static void formatNumber(String pattern, double value) { // Apply the pattern formatter.applyPattern ( pattern ); String formattedNumber = formatter.format(value); System.out.println("Number:" + value + ", Pattern:" + pattern + ", Formatted Number:" + formattedNumber); } } 上面的代码生成以下结果。
我们还可以使用方法将字符串解析为数字。方法返回类的对象。
我们可以使用类中的xxxValue()方法来获取原始值,其中xxx可以是byte,double,float,int,long和short。
import java.text.DecimalFormat; import java.text.ParsePosition;
public class Main { private static DecimalFormat formatter = new DecimalFormat();
public static void main(String[] args) {
讯享网// Parse a string to decimal number String str = "1,234.567"; String pattern = "#,."; formatter.applyPattern(pattern); // Create a ParsePosition object to specify the first digit of // number in the string. It is 1 in "1,234.567" // with the index 2. ParsePosition pp = new ParsePosition(2); Number numberObject = formatter.parse(str, pp); double value = numberObject.doubleValue(); System.out.println("Parsed Value is " + value); }
}
上面的代码生成以下结果。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/174932.html