首页 > 编程知识 正文

java字符串转日期,并格式化,java时间类型转换成字符串

时间:2023-05-06 20:43:21 阅读:265388 作者:2841

Sometimes we have to Convert String to Date in java program or convert Date to String in a different format for printing.

有时,我们必须在Java程序中将String转换为Date或以其他格式将Date转换为String才能打印。

将字符串转换为日期 (Convert String to Date)

Here is a simple scenario where we will have to convert String to Date in Java. The string is one of the most widely used Object in Java. If you are working in web services or web applications with form, you get a date in the form of the String object. So in the server side, we have to convert String to a Date object.

这是一个简单的场景,我们将不得不在Java中将String转换为Date。 字符串是Java中使用最广泛的对象之一。 如果您使用表单使用Web服务或Web应用程序,则会以String对象的形式获取日期。 因此,在服务器端,我们必须将String转换为Date对象。

将日期转换为字符串 (Convert Date to String)

Similarly while showing date information on any web page, we have to convert Date to String in the required format. It’s a very common process and you will see some form of date on almost all the websites.

同样,在任何网页上显示日期信息时,我们都必须将Date转换为所需格式的String。 这是一个非常常见的过程,您几乎会在所有网站上看到某种形式的日期。

在Java中将字符串转换为日期 (Convert String to Date in Java)

We have some specific classes in java for Date to String formatting. java.text.DateFormat is the abstract class for Date/Time formatting. java.text.SimpleDateFormat is the concrete class we use to convert String to Date and to convert Date to String in different formats.

我们在Java中有一些特定的类,用于从日期到字符串的格式设置。 java.text.DateFormat是日期/时间格式的抽象类 。 java.text.SimpleDateFormat是我们用来将String转换为Date以及将Date转换成不同格式的String的具体类。

Let’s see how to convert String to Date and convert Date to String in java program.

让我们看看如何在Java程序中将String转换为Date并将Date转换为String。

package com.journaldev.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 objectDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");try {// Convert String to Date in javaDate today = sdf.parse("14/11/2012");System.out.println("Date is : " + today.toString());// using localesdf = 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 JavaSystem.out.println("CHINESE Format Date : "+sdf.format(today));System.out.println("CANADA_FRENCH Format Date : "+sdf1.format(today));} catch (ParseException e) {e.printStackTrace();}}}

From example, it’s clear that we use parse(String str) method to convert String to Date object.

从示例中可以明显看出,我们使用parse(String str)方法将String转换为Date对象。

For converting Date to String, we use format(Date date) method. Note that both of these methods implementation is provided in DateFormat class and SimpleDateFormat inherits them through java inheritance.

为了将Date转换为String,我们使用format(Date date)方法。 请注意,这两个方法的实现都在DateFormat类中提供,并且SimpleDateFormat通过java继承继承它们。

DateFormat class supports TimeZone and Locale specific conversions also. That’s why you will see that the output of the above program varies based on locale information provided at the time of creating a SimpleDateFormat instance.

DateFormat类还支持TimeZone和Locale特定的转换。 这就是为什么您会看到上述程序的输出根据创建SimpleDateFormat实例时提供的语言环境信息而变化的原因。

DateFormat格式字符 (DateFormat format characters)

Like java regular expression, we have to use specific characters to create the pattern to use by DateFormat class. Here is the list of all the important characters we should know:

像Java正则表达式一样,我们必须使用特定的字符来创建要由DateFormat类使用的模式。 这是我们应该知道的所有重要字符的列表:

LetterDate or Time componentExampleGEra DesignatorAD, BCyYear2012, 12MMonth in yearAug, 08wWeek in year27, 52Wweek in month2, 4dDay in month12, 31DDay in year365, 123uDay number of week, 1=Monday1, 7aAM/PM markerAM, PMHhour in day (0-23)23khour in day (1-24)22Khour in AM/PM (0-11)10mminute in hour (0-59)23sSeconds in minute (0-59)43Smilliseconds (0-999)567zGeneral TimeZonePST, CST, GMTZRFC 822 TimeZone-0800XISO 8601 TimeZone-08, -08:00 信 日期或时间部分 例 G 时代代号 公元前 ÿ 年 2012,12 中号 一年中的月份 08年8月 w 一年中的一周 27、52 w ^ 每月的周 2 4 d 每月的一天 12、31 d 一年中的一天 365、123 ü 星期几,1 =星期一 1、7 一个 AM / PM标记 上午下午 H 一天中的小时(0-23) 23 ķ 一天中的小时(1-24) 22 ķ 上午/下午(0-11)小时 10 米 每小时的分钟数(0-59) 23 s 秒(0-59) 43 小号 毫秒(0-999) 567 ž 通用时区 PST,CST,GMT ž RFC 822时区 -0800 X ISO 8601时区 -08,-08:00 Java日期格式字符串 (Java Date Format String)

Let’s extend our program a bit to support multiple String formats while parsing to Date. This situation can arise when you have a web page or XML field that supports multiple formats for passing date as a string.

让我们对程序进行一些扩展,以在解析为Date时支持多种String格式。 当您的网页或XML字段支持将日期作为字符串传递的多种格式时,会出现这种情况。

package com.journaldev.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 usepublic 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 havefor (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 exceptionif (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 DateString[] 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");}}}}

In the above class, we are passing all the format’s of Date string that we are expecting and then stringToDate(String str) method use those to parse given String.

在上面的类中,我们传递了我们期望的所有日期字符串格式,然后stringToDate(String str)方法使用这些格式来解析给定的String。

Here is the output of the above program.

这是上面程序的输出。

10 NOV 2012 Date Object = Sat Nov 10 00:00:00 IST 201210/14/2012 Date Object = Sun Oct 14 00:00:00 IST 201210/14/2012 10:45:30 Date Object = Sun Oct 14 00:00:00 IST 2012ABC is not a valid datenull Date Object = null

Note that you should create static object for a list of formats in your application rather than initializing it all the time.

请注意,您应该为应用程序中的格式列表创建静态对象,而不是始终对其进行初始化。

You might also want to create Singleton class for this purpose.

为此,您可能还需要创建Singleton类。

DateFormat class is not thread-safe. So if you want thread safety, you need to create a wrapper class for SimpleDateFormat and implement synchronized format and parse methods that internally invokes DateFormat methods.

DateFormat类不是线程安全的。 因此,如果希望线程安全,则需要为SimpleDateFormat创建包装器类 ,并实现内部调用DateFormat方法的同步格式和解析方法。

Update: Java 8 new Date Time API provides easy and standard approach for handling parsing and date formatting, you should check it out at Java 8 Date tutorial.

更新 : Java 8新的Date Time API为处理解析和日期格式提供了简单而标准的方法,您应该在Java 8 Date教程中进行检查。

翻译自: https://www.journaldev.com/692/convert-string-date-java

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。