Log In Sign Up
How do I convert the date from one format to another date object in another format without using any
deprecated classes?
Ask Question
35
10
I'd like to convert a date in date1 format to a date object in date2 format.
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM dd, yyyy");
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyyMMdd");
Calendar cal = Calendar.getInstance();
cal.set(2012, 8, 21);
Date date = cal.getTime();
Date date1 = simpleDateFormat.parse(date);
Date date2 = simpleDateFormat.parse(date1);
println date1
println date2
java
share improve this question
asked Sep 19 '12 at 22:00
Phoenix
3,246 13 39 74
I have created a simple method to do this. refer to stackoverflow.com/a/40042733/4531507 – Rahul Sharma Oct 14 '16 at 12:34
9 Answers active oldest votes
103
Use SimpleDateFormat#format :
DateFormat originalFormat = new SimpleDateFormat("MMMM dd, yyyy", Locale.ENGLISH);
DateFormat targetFormat = new SimpleDateFormat("yyyyMMdd");
Date date = originalFormat.parse("August 21, 2012");
String formattedDate = targetFormat.format(date); // 20120821
Also note that parse takes a String , not a Date object, which is already parsed.
share improve this answer
edited Sep 19 '12 at 22:21
answered Sep 19 '12 at 22:01
João Silva
69.6k 23 132 144
This is what I tried and it threw an exception – Phoenix Sep 19 '12 at 22:08
you'd need to wrap Date parsedDate = simpleDateFormat1.parse(formattedDate); with try catch as it'd throw parseexception. – PermGenError Sep 19 '12 at 22:09
What are the exact inputs you are trying to parse? Try this demo ideone.com/Hr6B0. Perhaps you are passing an invalid Date ? – João Silva Sep 19 '12 at 22:11
My input is a string of this format August 21, 2012 and I need to save it as another string of format 20120821 – Phoenix Sep 19 '12 at 22:12
@Phoenix: Are you setting the Locale to Locale.ENGLISH of the first SimpleDateFormat ? Otherwise, if you are on a non-english Locale , August will not be parsed
correctly and will throw a ParseException. – João Silva Sep 19 '12 at 22:12
show 6 more comments
By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service.
tl;dr
LocalDate.parse(
"January 08, 2017" ,
DateTimeFormatter.ofPattern( "MMMM dd, uuuu" , Locale.US )
).format( DateTimeFormatter.BASIC_ISO_DATE )
Using java.time
The Question and other Answers use troublesome old date-time classes, now legacy, supplanted by the java.time classes.
You have date-only values, so use a date-only class. The LocalDate class represents a date-only value without time-of-day and without time zone.
String input = "January 08, 2017";
Locale l = Locale.US ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMMM dd, uuuu" , l );
LocalDate ld = LocalDate.parse( input , f );
Your desired output format is defined by the ISO 8601 standard. For a date-only value, the “expanded” format is YYYY-MM-DD such as 2017-01-08 and the
“basic” format that minimizes the use of delimiters is YYYYMMDD such as 20170108 .
I strongly suggest using the expanded format for readability. But if you insist on the basic format, that formatter is predefined as a constant on the
DateTimeFormatter class named BASIC_ISO_DATE .
String output = ld.format( DateTimeFormatter.BASIC_ISO_DATE );
See this code run live at IdeOne.com.
ld.toString(): 2017-01-08
output: 20170108
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date ,
Calendar , & SimpleDateFormat .
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find
some useful classes here such as Interval , YearWeek , YearQuarter , and more.
share improve this answer
edited May 23 '17 at 11:33
Community ♦
1 1
answered Feb 15 '17 at 4:28
Basil Bourque
111k 27 381 542
Using Java 8, we can achieve this as follows:
private static String convertDate(String strDate)
{
//for strdate = 2017 July 25
DateTimeFormatter f = new DateTimeFormatterBuilder().appendPattern("yyyy MMMM dd")
.toFormatter();
LocalDate parsedDate = LocalDate.parse(strDate, f);
DateTimeFormatter f2 = DateTimeFormatter.ofPattern("MM/d/yyyy");
String newDate = parsedDate.format(f2);
return newDate;
}
The output will be : "07/25/2017"
share improve this answer
answered Jul 26 '17 at 9:58
KayV
3,849 2 23 57
Please refer to the following method. It takes your date String as argument1, you need to specify the existing format of the date as argument2, and the result
(expected) format as argument 3.
Refer to this link to understand various formats: Available Date Formats
public static String formatDateFromOnetoAnother(String date,String givenformat,String resultformat) {
String result = "";
SimpleDateFormat sdf;
SimpleDateFormat sdf1;
try {
sdf = new SimpleDateFormat(givenformat);
sdf1 = new SimpleDateFormat(resultformat);
result = sdf1.format(sdf.parse(date));
}
catch(Exception e) {
e.printStackTrace();
return "";
}
finally {
sdf=null;
sdf1=null;
}
return result;
}
share improve this answer
edited May 4 '16 at 16:57
Peter Mortensen
13.7k 19 86 111
answered Feb 5 '15 at 9:05
ThmHarsh
450 6 5
Hope this will help someone.
public static String getDate(
String date, String currentFormat, String expectedFormat)
throws ParseException {
// Validating if the supplied parameters is null
if (date == null || currentFormat == null || expectedFormat == null ) {
return null;
}
// Create SimpleDateFormat object with source string date format
SimpleDateFormat sourceDateFormat = new SimpleDateFormat(currentFormat);
// Parse the string into Date object
Date dateObj = sourceDateFormat.parse(date);
// Create SimpleDateFormat object with desired date format
SimpleDateFormat desiredDateFormat = new SimpleDateFormat(expectedFormat);
// Parse the date into another format
return desiredDateFormat.format(dateObj).toString();
}
share improve this answer
answered Mar 30 '17 at 9:55
Dinesh Lomte
111 3
Try this
This is the simplest way of changing one date format to another
public String changeDateFormatFromAnother(String date){
@SuppressLint("SimpleDateFormat") DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
@SuppressLint("SimpleDateFormat") DateFormat outputFormat = new SimpleDateFormat("dd MMMM yyyy");
String resultDate = "";
try {
resultDate=outputFormat.format(inputFormat.parse(date));
} catch (ParseException e) {
e.printStackTrace();
}
return resultDate;
}
share improve this answer
edited Mar 11 '18 at 9:24
answered Mar 10 '18 at 17:16
Sunil
1,712 1 13 29
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
String fromDateFormat = "dd/MM/yyyy";
String fromdate = 15/03/2018; //Take any date
String CheckFormat = "dd MMM yyyy";//take another format like dd/MMM/yyyy
String dateStringFrom;
Date DF = new Date();
try
{
//DateFormatdf = DateFormat.getDateInstance(DateFormat.SHORT);
DateFormat FromDF = new SimpleDateFormat(fromDateFormat);
FromDF.setLenient(false); // this is important!
Date FromDate = FromDF.parse(fromdate);
dateStringFrom = new
SimpleDateFormat(CheckFormat).format(FromDate);
DateFormat FromDF1 = new SimpleDateFormat(CheckFormat);
DF=FromDF1.parse(dateStringFrom);
System.out.println(dateStringFrom);
}
catch(Exception ex)
{
System.out.println("Date error");
output:- 15/03/2018
15 Mar 2018
share improve this answer
answered Mar 15 '18 at 5:18
jalpa jogi
1
Kotlin equivalent of answer answered by João Silva
fun getFormattedDate(originalFormat: SimpleDateFormat, targetFormat: SimpleDateFormat, inputDate: String): String {
return targetFormat.format(originalFormat.parse(inputDate))
}
Usage (In Android):
getFormattedDate(
SimpleDateFormat(FormatUtils.d_MM_yyyy, Locale.getDefault()),
SimpleDateFormat(FormatUtils.d_MMM_yyyy, Locale.getDefault()),
dateOfTreatment
)
Note: Constant values:
// 25 Nov 2017
val d_MMM_yyyy = "d MMM yyyy"
// 25/10/2017
val d_MM_yyyy = "d/MM/yyyy"
share improve this answer
answered Aug 29 '18 at 10:28
Killer
1,936 2 19 38
While SimpleDateFormat is not officially deprecated yet, it is certainly both long outdated and notoriously troublesome. Today we have so much better in java.time , the
modern Java date and time API and its DateTimeFormatter . Yes, you can use it on Android. For older Android see How to use ThreeTenABP in Android Project . – Ole V.V. Aug
29 '18 at 14:18
I didn't knew about that. I will check it soon – Killer Aug 29 '18 at 15:58
-1
//Convert input format 19-FEB-16 01.00.00.000000000 PM to 2016-02-19 01.00.000 PM
SimpleDateFormat inFormat = new SimpleDateFormat("dd-MMM-yy hh.mm.ss.SSSSSSSSS aaa");
Date today = new Date();
Date d1 = inFormat.parse("19-FEB-16 01.00.00.000000000 PM");
SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd hh.mm.ss.SSS aaa");
System.out.println("Out date ="+outFormat.format(d1));
share improve this answer
answered Feb 19 '16 at 21:02
Karthik M
56 5
SimpleDateFormat is limited to parsing millisecond precision, and will corrupt the minutes/seconds if asked to go beyond that. – Robert Dean May 13 '16 at 12:24
Your Answer
Sign up or log in
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Name
Email
Required, but never shown
Post Your Answer
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Not the answer you're looking for? Browse other questions tagged java or ask your own question.
asked 6 years, 5 months ago
viewed 105,463 times
active 5 months ago
Linked
-1
convert date from one format to another in java
-2
How can I Convert timestamp String to Date in
Android
-4
How to convert dd/MM/yyyy format date to
ccyy/MM/dd format in java?
0
Subtring to get date in android
-2
How to validate dates in two different formats
-3
Convert date format from dd-mm-yyyy to YYMMDD
126
How to use ThreeTenABP in Android Project
12
How to convert Date to a particular format in
android?
3
Simpledateformat unparseable date
2
How to format a date String into desirable Date
format
see more linked questions…
Related
1990
How do I call one constructor from another in Java?
702
How do I convert from int to String?
224
Converting a date string to a DateTime object using
Joda Time library
32
Java : Cannot format given Object as a Date
1
convert string to date in java in format 2012-07-27
1
How to convert String to date object[without time]
275
How to parse/format dates with LocalDateTime?
(Java 8)
-3
How to convert a Gregorian calendar date format to
Julian date format?
Convert any incoming date format to standard
format in Java
-3
Convert Date to the same format as another Date
Hot Network Questions
Can I adapt code I wrote for work and release it as
open source
Was Opportunity's last message to Earth "My
battery is low and it's getting dark"?
Which Airport am I going to be at in Iceland if my
ticket says Reykjavik Keflavik Iceland
Why are right-wing politicians in the US typically
pro-Israel?
Determinant of a particular matrix.
PCB stackup for an 8-layer PCB
Can someone explain the theory behind the
changes in Superstition by Stevie Wonder?
Can a malware power on a computer?
Lying is illegal. How to make joking not an
offence?
I may have broken ESTA rules without knowing.
What to do now?
How to update BIOS on computer that won't boot
up?
Using throw to replace return in C++ non-void
functions
Does this image with a subject containing graffiti in
the background infringe on the graffiti artist's
copyright?
Grep remove line with 0 but not 0.2?
Why doesn't Russia build more missile defense
systems instead of complaining about NATO's
systems?
UCSD P-System: Why only 77 files per volume?
Is this an email from Apple or fraud?
The Highest Dice
Can a plane land on an aircraft carrier without
support from its crew?
Paying people not to vote at all
Can the cometd library be used in Salesforce to
listen to external buses?
How did Olaf survive all summers?
If you place a pencil in an opaque box and close
the box, does the pencil exist?
Are expensive material component costs too
specific?
question feed
STACK OVERFLOW
Questions
Jobs
Developer Jobs Directory
Salary
Calculator
Help
Mobile
Disable Responsiveness
PRODUCTS
Teams
Talent
Engagement
Enterprise
COMPANY
About
Press
Work Here
Legal
Privacy Policy
Contact Us
STACK EXCHANGE
NETWORK
Technology
Life / Arts
Culture / Recreation
Science
Other
Blog
Facebook
Twitter
LinkedIn
site design / logo © 2019 Stack Exchange Inc; user contributions licensed under cc by-sa 3.0 with attribution required. rev 2019.2.15.32899