在Java中将字符串转换为日期,将日期转换为字符串
有时我们必须在Java程序中将String转换为Date或者将日期转换为另一种格式的String才能进行打印。
将字符串转换为日期
这是一个简单的场景,我们将不得不在Java中将String转换为Date。
字符串是Java中使用最广泛的对象之一。
如果您使用表单使用Web服务或者Web应用程序,则会以String对象的形式获取日期。
因此,在服务器端,我们必须将String转换为Date对象。
将日期转换为字符串
同样,在任何网页上显示日期信息时,我们都必须将Date转换为所需格式的String。
这是一个非常常见的过程,几乎所有上都会显示某种日期形式。
在Java中将字符串转换为日期
我们在Java中有一些特定的类,用于从日期到字符串的格式设置。
java.text.DateFormat是日期/时间格式的抽象类。
java.text.SimpleDateFormat是我们用来将String转换为Date以及将Date转换成不同格式的String的具体类。
让我们看看如何在Java程序中将String转换为Date并将Date转换为String。
package com.theitroad.util;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
* Convert String to Date in Java Example
* Convert Date to String in Java Example
*
* @author pankaj
*
*/
public class DateUtils {
public static void main(String[] args) {
//initialize SimpleDateFormat object
DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
try {
//Convert String to Date in java
Date today = sdf.parse("14/11/2012");
System.out.println("Date is : " + today.toString());
//using locale
sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.CHINESE);
DateFormat sdf1 = new SimpleDateFormat("dd-MMM-yyyy", Locale.CANADA_FRENCH);
today = new Date();
System.out.println("Default Date is : " + today.toString());
//Convert Date to String in Java
System.out.println("CHINESE Format Date : "+sdf.format(today));
System.out.println("CANADA_FRENCH Format Date : "+sdf1.format(today));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
从示例中可以明显看出,我们使用了parse(String str)方法将String转换为Date对象。
为了将Date转换为String,我们使用format(Date date)方法。
请注意,这两种方法的实现都在DateFormat类中提供,SimpleDateFormat通过Java继承继承它们。
DateFormat类还支持TimeZone和区域设置特定的转换。
这就是为什么您会看到上述程序的输出根据创建SimpleDateFormat实例时提供的语言环境信息而变化的原因。
DateFormat格式字符
像Java正则表达式一样,我们必须使用特定的字符来创建要由DateFormat类使用的模式。
这是我们应该知道的所有重要字符的列表:
| Letter | Date or Time component | Example |
|---|---|---|
| G | Era Designator | AD, BC |
| y | Year | 2012, 12 |
| M | Month in year | Aug, 08 |
| w | Week in year | 27, 52 |
| W | week in month | 2, 4 |
| d | Day in month | 12, 31 |
| D | Day in year | 365, 123 |
| u | Day number of week, 1=Monday | 1, 7 |
| a | AM/PM marker | AM, PM |
| H | hour in day (0-23) | 23 |
| k | hour in day (1-24) | 22 |
| K | hour in AM/PM (0-11) | 10 |
| m | minute in hour (0-59) | 23 |
| s | Seconds in minute (0-59) | 43 |
| S | milliseconds (0-999) | 567 |
| z | General TimeZone | PST, CST, GMT |
| Z | RFC 822 TimeZone | -0800 |
| X | ISO 8601 TimeZone | -08, -08:00 |
Java日期格式字符串
让我们扩展程序,以在解析为日期时支持多种字符串格式。
当您的网页或者XML字段支持将日期作为字符串传递的多种格式时,会出现这种情况。
package com.theitroad.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class StringToDateUtil {
private List<SimpleDateFormat> sdfList;
//set the List of Format's you want to use
public StringToDateUtil(List<SimpleDateFormat> sdfList) throws Exception {
if (sdfList == null)
throw new Exception("sdfList can't be null");
this.sdfList = sdfList;
}
public Date stringToDate(String str) throws Exception {
if (str == null)
return null;
Date date = null;
//parse the input String with list of SimpleDateFormats we have
for (SimpleDateFormat sdf : sdfList) {
try {
date = sdf.parse(str);
} catch (ParseException pe) {
//do nothing, we need to try other format
}
//check if parsed successfully?
if (date != null)
break;
}
//return date if parsed successfully or else throw exception
if (date != null)
return date;
throw new Exception("invalid format for String:" + str);
}
public static void main(String args[]) throws Exception {
List<SimpleDateFormat> formatList = new ArrayList<>();
formatList.add(new SimpleDateFormat("dd MMM yyyy"));
formatList.add(new SimpleDateFormat("M/dd/yyyy"));
formatList.add(new SimpleDateFormat("M/dd/yyyy hh:mm:ss a"));
StringToDateUtil sdUtil = new StringToDateUtil(formatList);
//Lets format some String to Date
String[] arr = { "10 NOV 2012", "10/14/2012", "10/14/2012 10:45:30", "ABC", null };
for (String str : arr) {
try {
System.out.println(str + " Date Object = " + sdUtil.stringToDate(str));
} catch (Exception e) {
System.out.println(str + " is not a valid date");
}
}
}
}
在上面的类中,我们传递了我们期望的所有日期字符串格式,然后stringToDate(String str)方法使用这些格式来解析给定的String。
这是上面程序的输出。
10 NOV 2012 Date Object = Sat Nov 10 00:00:00 IST 2012 10/14/2012 Date Object = Sun Oct 14 00:00:00 IST 2012 10/14/2012 10:45:30 Date Object = Sun Oct 14 00:00:00 IST 2012 ABC is not a valid date null Date Object = null
请注意,您应该为应用程序中的格式列表创建静态对象,而不是始终对其进行初始化。
为此,您可能还想创建Singleton类。
DateFormat类不是线程安全的。
因此,如果您希望线程安全,则需要为SimpleDateFormat创建包装器类,并实现内部调用DateFormat方法的同步格式和解析方法。
更新:Java 8新的Date Time API为处理解析和日期格式提供了简单而标准的方法,您应该在Java 8 Date教程中进行检查。

