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类使用的模式。 这是我们应该知道的所有重要字符的列表:

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
日期或时间部分
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 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

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

在Java中将字符串转换为日期,将日期转换为字符串相关推荐

  1. Java中将对象中属性值为空字符串设置为null

    业务逻辑中需要将对象中为空字符串的属性转换为null,简单的一种方式是前端JS控制,如果为空字符串则不传到后台,后台接收到没有值的属性默认为null.这种方式会导致JS繁琐.下面用后台通过反射的方式来 ...

  2. java xml字符串提取元素,如何从Java中将子元素从XML提取到字符串?

    你是对的,使用标准的XML API,这不是一个好方法 – 这是一个例子(可能是错误的;它运行,但我很久以前写过它). import javax.xml.*; import javax.xml.pars ...

  3. 如何在Java中将字符串转换为日期

    将Java(或任何编程语言)中的字符串转换为日期是一项基本技能,对于在项目上进行工作很有用.有时,使用字符串表示日期,然后将其转换为Date对象以供进一步使用是更容易的. 在本文中,我们将介绍许多可用 ...

  4. JAVA日期转换YY和yy_在java中将dateTime转换为dd / MM / yy格式的日期

    我有一辆Joda DateTime2012-12-31T13:32:56.483+13:00.我想把它转换成dd/MM/yy格式的日期.所以我希望代码能返回-31/12/12这样的日期. 代码- // ...

  5. java date truncate_在Java中将dateTime转换为dd / mm / yy格式的日期

    小编典典 正如我最初所说,Date对象没有固有的格式.java.util.Date持有毫秒时间值,代表日期和时间.通过选择DateFormat,可以从字符串解析日期或将日期格式化为字符串. 可以按照规 ...

  6. JAVA字符串转日期或日期转字符串

    用法: SimpleDateFormat sdf = new SimpleDateFormat( " yyyy-MM-dd HH:mm:ss " ); 这一行最重要,它确立了转换的 ...

  7. java日期存入数据库_怎样在Java中将日期转化插入到数据库

    展开全部 Java中将e5a48de588b662616964757a686964616f31333339653664日期转化插入到数据库: public static Date dateTimeSt ...

  8. 使用Python将字符串转换为格式化的日期时间字符串

    我正在尝试将字符串"20091229050936"转换为"2009年12月29日(UTC)" >>>import time >>& ...

  9. java时间戳龙_Java时间戳与日期格式字符串的互转

    Java时间戳与日期格式字符串的互转 import java.text.SimpleDateFormat; import java.util.Date; public class DateUtil { ...

最新文章

  1. oracle闪回 分区,Oracle 闪回区(Oracle Flash recovery area)
  2. linux I/O--五种I/O模型(一)
  3. VB6.0 怎样启用控件comdlg32.ocx
  4. 如何获取不同网站的favicon默认图标
  5. Silverlight 4 新特性之Silverlight as Drop Target
  6. Kafka REST Proxy for MapR Streams入门
  7. 人生也要一个中心两个基本点(转载)
  8. GNN上用到的Tasks,Dataset and Benchmark
  9. mysql 连接错误The server time zone value ‘?????????‘
  10. 基于算法的建模--小结
  11. GMQ区块链生态系统平行链,未来将应用于众多产业
  12. 高通设备找不到连接QXDM的端口
  13. android listview滑动分页加载数据,android中listview分页加载数据
  14. C#实现Word批量转换Pdf
  15. 神经网络之父Hinton介绍及其论文介绍
  16. JavaWeb笔记(五)后端
  17. SpriteKit从零开始~Physics and Collisions
  18. 柱状图折线图混合使用
  19. 快递查询方法一键查询物流信息
  20. Oracle计算时间差

热门文章

  1. 【NOIP2016提高A组模拟10.15】算循环
  2. libusb-win32学习笔记(一)
  3. C++两种编写单件模式方法对比
  4. [转载] python classmethod存在的意义_@classmethod和@staticmethod对初学者的意义?
  5. [转载] 使用Python+OpenCV实现在视频中某对象后添加图像
  6. 抽象类和接口到底是什么“垃圾“——教你分类
  7. __new__()方法的使用和实例化
  8. MyEclipse项目里面出现红叉的解决方案?
  9. MVC HtmlHelper listbox用法
  10. 汇编3-返回以及优化