In this tutorial, we will show you how to convert a String to java.util.Date. Many Java beginners are stuck in the Date conversion, hope this summary guide will helps you in some ways.

// String -> Date
SimpleDateFormat.parse(String);

// Date -> String
SimpleDateFormat.format(date);
Refer to table below for some of the common date and time patterns used in java.text.SimpleDateFormat, refer to this JavaDoc

Letter Description Examples
y Year 2013
M Month in year July, 07, 7
d Day in month 1-31
E Day name in week Friday, Sunday
a Am/pm marker AM, PM
H Hour in day 0-23
h Hour in am/pm 1-12
m Minute in hour 0-60
s Second in minute 0-60
Note
You may interest at this Java 8 example – How to convert String to LocalDate
1. String = 7-Jun-2013
If 3 ‘M’, then the month is interpreted as text (Mon-Dec), else number (01-12).

TestDateExample1.java

package com.mkyong.date;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TestDateExample1 {

public static void main(String[] argv) {

SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
String dateInString = "7-Jun-2013";

try {

Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));

} catch (ParseException e) {
e.printStackTrace();
}

}

}
Output

Fri Jun 07 00:00:00 MYT 2013
07-Jun-2013
2. String = 07/06/2013
TestDateExample2.java

package com.mkyong.date;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TestDateExample2 {

public static void main(String[] argv) {

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateInString = "07/06/2013";

try {

Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));

} catch (ParseException e) {
e.printStackTrace();
}

}

}
Output

Fri Jun 07 00:00:00 MYT 2013
07/06/2013
3. String = Fri, June 7 2013
TestDateExample3.java

package com.mkyong.date;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TestDateExample3 {

public static void main(String[] argv) {

SimpleDateFormat formatter = new SimpleDateFormat("E, MMM dd yyyy");
String dateInString = "Fri, June 7 2013";

try {

Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));

} catch (ParseException e) {
e.printStackTrace();
}

}

}
Output

Fri Jun 07 00:00:00 MYT 2013
Fri, Jun 07 2013
4. String = Friday, Jun 7, 2013 12:10:56 PM
TestDateExample4.java

package com.mkyong.date;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TestDateExample4 {

public static void main(String[] argv) {

SimpleDateFormat formatter = new SimpleDateFormat("EEEE, MMM dd, yyyy HH:mm:ss a");
String dateInString = "Friday, Jun 7, 2013 12:10:56 PM";

try {

Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));

} catch (ParseException e) {
e.printStackTrace();
}

}

}
Output

Fri Jun 07 12:10:56 MYT 2013
Friday, Jun 07, 2013 12:10:56 PM
5. String = 2014-10-05T15:23:01Z
Z suffix means UTC, java.util.SimpleDateFormat doesn’t parse it correctly, you need to replace the suffix Z with ‘+0000’.

TestDateExample5.java

package com.mkyong.date;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TestDateExample5 {

public static void main(String[] argv) {

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String dateInString = "2014-10-05T15:23:01Z";

try {

Date date = formatter.parse(dateInString.replaceAll("Z$", "+0000"));
System.out.println(date);

System.out.println("time zone : " + TimeZone.getDefault().getID());
System.out.println(formatter.format(date));

} catch (ParseException e) {
e.printStackTrace();
}

}

}
Output

Sun Oct 05 23:23:01 MYT 2014
time zone : Asia/Kuala_Lumpur
2014-10-05T23:23:01+0800
In Java 8, you can convert it into a java.time.Instant object, and display it with a specified time zone.

TestDateExample6.java

package com.mkyong.date;

import java.time.*;

public class TestDateExample6 {

public static void main(String[] argv) {

String dateInString = "2014-10-05T15:23:01Z";

Instant instant = Instant.parse(dateInString);

System.out.println(instant);

//get date time only
LocalDateTime result = LocalDateTime.ofInstant(instant, ZoneId.of(ZoneOffset.UTC.getId()));

System.out.println(result);

//get date time + timezone
ZonedDateTime zonedDateTime = instant.atZone(ZoneId.of("Africa/Tripoli"));
System.out.println(zonedDateTime);

//get date time + timezone
ZonedDateTime zonedDateTime2 = instant.atZone(ZoneId.of("Europe/Athens"));
System.out.println(zonedDateTime2);

}

}
Output

2014-10-05T15:23:01Z
2014-10-05T15:23:01
2014-10-05T17:23:01+02:00[Africa/Tripoli]
2014-10-05T18:23:01+03:00[Europe/Athens]

http://www.mkyong.com/java/how-to-convert-string-to-date-java/
http://www.mkyong.com/tutorials/java-date-time-tutorials/

How to convert String to Date – Java的更多相关文章

  1. Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'xxx': no matching editors or conversion strategy found

    今天在完成项目的时候遇到了下面的异常信息: 04-Aug-2014 15:49:27.894 SEVERE [http-apr-8080-exec-5] org.apache.catalina.cor ...

  2. 【spring boot】spring boot 前台GET请求,传递时间类型的字符串,后台无法解析,报错:Failed to convert from type [java.lang.String] to type [java.util.Date]

    spring boot 前台GET请求,传递时间类型的字符串,后台无法解析,报错:Failed to convert from type [java.lang.String] to type [jav ...

  3. 完美解决报错Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'

    Failed to convert value of type 'java.lang.String' to required type 'java.util.Date' 首先这个错误的意思是 前台页面 ...

  4. Failed to convert from type [java.lang.String] to type [java.util.Date] for value '2020-02-06'; nested exception is java.lang.IllegalArgumentException]解决

    今天做springbook项目前端输入日期传到数据库保存报了一下错误 Whitelabel Error Page This application has no explicit mapping fo ...

  5. Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDate';

    springboot jdbc查询使用LocalDate报:Failed to convert value of type 'java.lang.String' to required type 'j ...

  6. How to convert any valid date string to a DateTime.

    DateTimeFormatInfo pattern = new DateTimeFormatInfo() { ShortDatePattern = "your date pattern&q ...

  7. Java:String和Date、Timestamp之间的转

    Java:String和Date.Timestamp之间的转 一.String与Date(java.util.Date)互转 1.1 String -> Date String dateStr  ...

  8. Java:String和Date、Timestamp之间的转换

    一.String与Date(java.util.Date)互转 1.1 String -> Date String dateStr = "2016-9-28 12:25:55" ...

  9. 解决spring mvc 上传报错,Field [] isn't an enum value,Failed to convert value of type 'java.lang.String[]' to required type '

    没有选择附件,但是点击上传按钮的时候会报错. 之前不选择文件,直接上传空文件是可以的,后来不知道改了什么就不行了. 错误信息: -- :: [http--] TRACE org.springframe ...

随机推荐

  1. WebSocket【转】

    1.什么是WebSocket WebSocket 是一种自然的全双工.双向.单套接字连接.使用WebSocket,你的HTTP 请求变成打开WebSocket 连接(WebSocket 或者WebSo ...

  2. Java Spring Quartz 定时任务

    公司需要使用JAVA的WebServer完成简单的定时跑任务的工作.其他例如:每隔30分钟执行锁定用户解锁任务. Quartz 在开源任务调度框架中的翘首,它提供了强大任务调度机制,难能可贵的是它同时 ...

  3. python 爬虫资料

    API Requests PyQuery http://www.tuicool.com/articles/UZrmUb2 http://blog.csdn.net/cnmilan/article/de ...

  4. C#的ThreadStart 和 Thread

    多线程,new Thread(t1);和new Thread(new ThreadStart(t1));有什么区别 没有区别. 前者,是c#的语法.也就是说是编译器帮你改写为第二种形式. 因此你要搞清 ...

  5. Changing the Language Used in ODI Studio

    odi.conf中加入区域和语言设置 修改 "$ODI_HOME\odi\studio\bin\odi.conf"    ( D:\Oracle\Middleware\Oracle ...

  6. kettle的安装、配置与运行

      1.下载与安装 官方下载地址:https://community.hitachivantara.com/docs/DOC-1009855 下载好后,解压,还可以对该目录进行重命名. 2.环境配置 ...

  7. 链接sql数据库并输出csv文件

    __author__ = 'chunyang.wu' #作者:SelectDB # -*- coding: utf-8 -*- import MySQLdb import os os.environ[ ...

  8. oracle初始化化表空间用户权限

    oracle单实例安装完毕,需要初始化表空间.用户.等信息.不积跬步,何以至千里! 用sys账户登录oracle数据库,以此来完成所有操作! 01.创建临时表空间 create temporary t ...

  9. 【原创视频教程】SqlServer2008视频教程[共9集]

    这些视频都是13年-14年两年里面录制的,怀着一份创造之心, 可能说得不对,或者说得肤浅,望见谅....也请指正... 谢谢你的支持.. 更多资料:北盟网 www.bamn.cn ---------- ...

  10. Easyui入门视频教程 第05集---Easyui复杂布局

    目录 ----------------------- Easyui入门视频教程 第09集---登录完善 图标自定义   Easyui入门视频教程 第08集---登录实现 ajax button的使用  ...