Converting string to a formatted date - java

I am trying to convert a string to proper date format using Java's SimpleDateFormat. For some reason, it's not working with certain months like "Mar", "May", "Oct", and "Dec." Can somebody help me? It works fine for all other months.
import java.sql.Date;
import java.text.SimpleDateFormat;
import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;
public class test {
public static void main(String args[]) throws java.text.ParseException {
try {
SimpleDateFormat parse = new SimpleDateFormat("dd. MMM yyyy hh:mm:ss");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//why this doesn't work with certain months like Mar, May, Oct, and Dec? otherwise it works fine
String dateTime = "01. Jun 2010 15:30:32";
//String dateTime = "07. Mar 2011 15:20:10";
//String dateTime = "07. May 2011 15:20:10";
//String dateTime = "07. Oct 2011 15:20:10";
//String dateTime = "07. Dec 2011 15:20:10";
java.util.Date parsed =parse.parse(dateTime);
System.out.println("formatted: " + formatter.format(parsed));
} catch(ParseException e) {
System.out.println("Caught " + e);
}
}
}

You need to set the locale on SimpleDateFormat, otherwise the platform default locale will be used for month names. You can do that by passing it as 2nd argument to the SimpleDateFormat constructor. If you want to work with English formatted month names, pass Locale.ENGLISH.
new SimpleDateFormat("dd. MMM yyyy hh:mm:ss", Locale.ENGLISH);
By the way, you can learn about your platform default locale by
System.out.println(Locale.getDefault());
This is configureable at OS level (in Windows control panel, for example) and as JVM argument.

Related

How can i convert String to Date when it has "TRT" in it

String sDate = "06.08.2020" // 06 day 08 month 2020 is year
This is the date i have in my txt file. I use them in JTable. To sort the table i convert them to date with this DateFormatter.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
And it does convert the string to date as this.
LocalDate date = LocalDate.parse(sDate,formatter);
//The date : Thu Aug 06 00:00:00 TRT 2020
Now i need to convert it like the first date 06.08.2020.
But i can't use date as input. Because i get it from JTable so i get it as String.
So i tryed this code.
String sDate1 = "Thu Aug 06 00:00:00 TRT 2020";// The date i get from JTable
LocalDate lastdate = LocalDate.parse(sDate1,formatter);
sDate1 = formatter.format(lastdate);
But i get an error as this Text 'Thu Aug 06 00:00:00 TRT 2020' could not be parsed at index 0.
So this cone not works fine : LocalDate lastdate = LocalDate.parse(sDate1,formatter);
I cant see where is the problem.
I cannot reproduce the behaviour you describe. The following code worked fine for me:
import java.util.*;
import java.text.*;
public class MyClass {
public static void main(String args[]) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
String date = "06.08.2020";
Date date1 = sdf.parse(date);
String result = sdf.format(date1);
System.out.println("Date = " + result);
}
}
Output: Date = 06.08.2020
That being said, if at all possible you should switch to the new java.time.* API.
Where your code failed:
SimpleDateFormat sdf1=new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
String dateStr = "06.08.2020";
sdf1.parse(dateStr);
As you can see, the pattern of the SimpleDateFormat and that of the date string do not match and therefore, this code will throw ParseException.
How to make it work?
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
String dateStr = "06.08.2020";
Date date = sdf.parse(dateStr);
You must have already got why it worked. It worked because the pattern of the SimpleDateFormat matches with that of the dateStr string.
Can I format the Date object (i.e. date) into the original string?
Yes, just use the same format which you used to parse the original string as shown below:
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
String dateStr = "06.08.2020";
Date date = sdf.parse(dateStr);
// Display in the default format
System.out.println(date);
// Format into the string
dateStr = sdf.format(date);
System.out.println(dateStr);
A piece of advice:
I recommend you switch from the outdated and error-prone java.util date-time API and SimpleDateFormat to the modern java.time date-time API and the corresponding formatting API (package, java.time.format). Learn more about the modern date-time API from Trail: Date Time.
Using the modern date-time API:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
String dateStr = "06.08.2020";
LocalDate date = LocalDate.parse(dateStr, formatter);
// Display in the default format
System.out.println(date);
// Format into the string
dateStr = formatter.format(date);
System.out.println(dateStr);
I don't see any difference using the legacy API and the modern API:
That's true for this simple example but when you will need to do complex operations using date and time, you will find the modern date-time API smart and clean while the legacy API complex and error-prone.
Demo:
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// Given date-time string
String strDate = "Thu Aug 06 00:00:00 TRT 2020";
// Replace TRT with standard time-zone string
strDate = strDate.replace("TRT", "Europe/Istanbul");
// Define formatter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzzz yyyy");
// Parse the date-time string into ZonedDateTime
ZonedDateTime zdt = ZonedDateTime.parse(strDate, formatter);
System.out.println(zdt);
// If you wish, convert ZonedDateTime into LocalDateTime
LocalDateTime ldt = zdt.toLocalDateTime();
System.out.println(ldt);
}
}
Output:
2020-08-06T00:00+03:00[Europe/Istanbul]
2020-08-06T00:00

How to convert mm/dd/yy string to "Monday 7th Jan"

I have a database file with mm/dd/yy values for events, and I want to display the date as something similar to "Day(word), day(number), month(word)".
01/07/19 into
Monday 4th Jan or Monday 4 Jan or something similar.
Try something like this:
LocalDate.of(2019, 3, 2).format(DateTimeFormatter.ofPattern("EEE dd MMM YYYY"))
You can use SimpleDateFormat to convert the string to date and then convert back to String like this :
DateFormat format1 = new SimpleDateFormat("MM-dd-yyyy");
Date date = format1.parse("01-01-2019");
DateFormat format2 = new SimpleDateFormat("MMMMM dd, yyyy");
String dateString = format2.format(date);
System.out.println(dateString); //<- prints January 01, 2019
How to use the SimpleDateFormat?
Java provides a class called a SimpleDateFormat that allows you to format and parse dates in the as per your requirements.
You can use the above characters to specify the format - For example:
1) Date format required: 2019.01.01 20:20:45 PST
The appropriate date format specified will be- yyyy.MM.dd HH:mm:ss zzz
2) Date format required:09:30:00 AM 01-Jan-2019
The appropriate date format specified will be-hh:mm:ss a dd-MMM-yyyy
Tip: Be careful with the letter capitalization. If you mistake M with m, you will undesired results!
Let's learn this with a code example.
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestDates_Format {
public static void main(String args[]) {
Date objDate = new Date(); // Current System Date and time is assigned to objDate
System.out.println(objDate);
String strDateFormat = "hh:mm:ss a dd-MMM-yyyy"; //Date format is Specified
SimpleDateFormat objSDF = new SimpleDateFormat(strDateFormat); //Date format string is passed as an argument to the Date format object
System.out.println(objSDF.format(objDate)); //Date formatting is applied to the current date
}
}
Output :
Sat Mar 02 16:37:59 UTC 2019
04:37:59 PM 02-Mar-2019
Have a nice day !

Format date and time in String format from an API response [duplicate]

This question already has answers here:
Parsing ISO_INSTANT and similar Date Time Strings
(4 answers)
Java / convert ISO-8601 (2010-12-16T13:33:50.513852Z) to Date object
(4 answers)
Closed 5 years ago.
I'm using the Guardian API to get recent news stories about football.
I want to show date and time info to the user, but not in the format the API throws it back to me.
When requesting webPublicationDate after querying http://content.guardianapis.com/search?page-size=10&section=football&show-tags=contributor&api-key=test I get the response in this format:
2017-06-22T16:18:04Z
Now, I want the date and time info in this format:
e.g. Jun 21, 2017 and 16:18 or 4:18 pm.
While I basically know to format a Date object properly into this format:
/**
* Return the formatted date string (i.e. "Mar 3, 1984") from a Date object.
*/
private String formatDate(Date dateObject) {
SimpleDateFormat dateFormat = new SimpleDateFormat("LLL dd, yyyy");
return dateFormat.format(dateObject);
}
/**
* Return the formatted date string (i.e. "4:30 PM") from a Date object.
*/
private String formatTime(Date dateObject) {
SimpleDateFormat timeFormat = new SimpleDateFormat("h:mm a");
return timeFormat.format(dateObject);
}
But I can't seem to convert the response I get into a Date object.
You can format the text this way:
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();
}
}
}
Z suffix means UTC, java.util.SimpleDateFormat doesn’t parse it correctly, you need to replace the suffix Z with ‘+0000’.
Code from here: https://www.mkyong.com/java/how-to-convert-string-to-date-java/
Instead of directly working with SimpleDateFormat (as this old API has lots of problems and design issues), you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. To use it in Android, you'll also need the ThreeTenABP (more on how to use it here).
The main classes to be used are org.threeten.bp.ZonedDateTime (which can parse the date/time input) and org.threeten.bp.format.DateTimeFormatter (to control the output format).
If you are reading this field (2017-06-22T16:18:04Z) as a String, you can create a ZonedDateTime like this:
ZonedDateTime z = ZonedDateTime.parse("2017-06-22T16:18:04Z");
If you already have a java.util.Date object, you can convert it using org.threeten.bp.DateTimeUtils with a org.threeten.bp.ZoneOffset:
Date date = // get java.util.Date
ZonedDateTime z = DateTimeUtils.toInstant(date).atZone(ZoneOffset.UTC);
In the end, the ZonedDateTime object will have the webPublicationDate value.
To get the different output formats, just create one DateTimeFormatter for each format. In the examples below, I also use java.util.Locale class to make sure the month names are in English:
// for Mar 3, 1984
DateTimeFormatter f1 = DateTimeFormatter.ofPattern("MMM d, yyyy", Locale.ENGLISH);
// for 4:40 PM
DateTimeFormatter f2 = DateTimeFormatter.ofPattern("h:mm a", Locale.ENGLISH);
// for 16:18
DateTimeFormatter f3 = DateTimeFormatter.ofPattern("HH:mm", Locale.ENGLISH);
System.out.println(f1.format(z)); // Jun 22, 2017
System.out.println(f2.format(z)); // 4:18 PM
System.out.println(f3.format(z)); // 16:18
The output is:
Jun 22, 2017
4:18 PM
16:18
Note that it uses the UTC timezone (the Z in 2017-06-22T16:18:04Z). If you want to display the date and time in another timezone, just use the org.threeten.bp.ZoneId class:
System.out.println(f3.format(z.withZoneSameInstant(ZoneId.of("Europe/London")))); // 17:18
The output is 17:18 (becase London is in summer time now).
Note that the API uses IANA timezones names (always in the format Continent/City, like America/Sao_Paulo or Europe/Berlin).
Avoid using the 3-letter abbreviations (like CST or PST) because they are ambiguous and not standard. To find the timezone that better suits each region, use the ZoneId.getAvailableZoneIds() method and check which one fits best for your use cases.
If you don't want to add another dependency to your project and use SimpleDateFormat, you do something similar (create one parser and 3 output formatters, and use English locale). Also don't forget to set the timezone - I'm using UTC below, but you can change it to whatever timezone you want.
// parse date
String dateInString = "2017-06-22T16:18:04Z";
SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
Date date = parser.parse(dateInString);
// create output formatters (set timezone to UTC)
TimeZone utc = TimeZone.getTimeZone("UTC");
SimpleDateFormat s1 = new SimpleDateFormat("MMM d, yyyy", Locale.ENGLISH);
s1.setTimeZone(utc);
SimpleDateFormat s2 = new SimpleDateFormat("h:mm a", Locale.ENGLISH);
s2.setTimeZone(utc);
SimpleDateFormat s3 = new SimpleDateFormat("HH:mm", Locale.ENGLISH);
s3.setTimeZone(utc);
System.out.println(s1.format(date));
System.out.println(s2.format(date));
System.out.println(s3.format(date));
The output will be the same:
Jun 22, 2017
4:18 PM
16:18

Add colon to 24 hour time in Java?

I have a date in the format MM/DD/YYYY and time in the format HHMM (24 hour time w/o the colon). Both of these strings are in an array. I would like to store this as one string - maybe something like "MM-DD-YYYY HH:MM" - and then be able to convert it to a written date like "January 1, 2014 16:15" when I am showing it to the user. How can I do this?
This is the code that I have:
String date = "05/27/2014 23:01";
Date df = new SimpleDateFormat("MM/DD/YYYY HH:mm").parse(date);
System.out.println(df);
However this is what I get: "Sun Dec 29 23:01:00 EST 2013"
The output I am looking for is: "December 29, 2013 23:01"
SimpleDateFormat is the way to go; to parse your Strings in the required meaningful date and time formats and finally print your date as a required String.
You specify the 2 formats as follows:
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat timeFormat = new SimpleDateFormat("HHmm");
Considering a simple hardcoded array of date and time (not the best way to show but your question calls it an array):
String[] array = { "12/31/2013", "1230" };
You would have to set these parsed dates in a Calendar instance:
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR, time.getHours());
cal.add(Calendar.MINUTE, time.getMinutes());
Finally format your date using the same SimpleDateFormat
SimpleDateFormat newFormat = new SimpleDateFormat("MMMM dd, yyyy 'at' hh:mm");
Here is the complete working code:
public class DateExample {
public static void main(String[] args) {
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat timeFormat = new SimpleDateFormat("HHmm");
String[] array = { "12/31/2013", "1230" };
try {
Date date = dateFormat.parse(array[0]);
Date time = timeFormat.parse(array[1]);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR, time.getHours());
cal.add(Calendar.MINUTE, time.getMinutes());
SimpleDateFormat newFormat = new SimpleDateFormat(
"MMMM dd, yyyy 'at' hh:mm");
String datePrint = newFormat.format(cal.getTime());
System.out.println(datePrint);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The output:
December 31, 2013 at 12:30
Unfortunately, none of the existing answers has mentioned the root cause of the problem which is as follows:
You have used D (which specifies Day in year) instead of d (Day in month).
You have used Y (which specifies Week year) instead of y (Year).
Learn more about it at the documentation page. Now that you have understood the root cause of the problem, let's focus on the solution using the best standard API of the time.
java.time
The legacy date-time API (java.util date-time types and their formatting API, SimpleDateFormat) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time, the modern date-time API*.
I would solve it in the following steps:
Parse the date string into LocalDate.
Parse the time string into LocalTime.
Combine the objects of LocalDate and LocalTime to obtain an object of LocalDateTime.
Format the object of LocalDateTime into the desired pattern.
Demo using the modern API:
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// 1. Parse the date string into `LocalDate`.
DateTimeFormatter dateParser = DateTimeFormatter.ofPattern("M/d/u", Locale.ENGLISH);
LocalDate date = LocalDate.parse("01/01/2014", dateParser);
// 2. Parse the time string into `LocalTime`.
DateTimeFormatter timeParser = DateTimeFormatter.ofPattern("HHmm", Locale.ENGLISH);
LocalTime time = LocalTime.parse("1615", timeParser);
// 3. Combine date and time to obtain an object of `LocalDateTime`.
LocalDateTime ldt = date.atTime(time);
// 4. Format the object of `LocalDateTime` into the desired pattern.
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("MMMM d, uuuu HH:mm", Locale.ENGLISH);
String output = dtfOutput.format(ldt);
System.out.println(output);
}
}
Output:
January 1, 2014 16:15
Learn more about the the modern date-time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
You can use java.text.DateFormat class to convert date to string(format method), and string to date(parse method).
You can use SimpleDateFormat both to parse Strings into dates and to format Dates back into Strings. Here's your example:
SimpleDateFormat parser = new SimpleDateFormat("MM/DD/YYYY HH:mm");
SimpleDateFormat formatter = new SimpleDateFormat("MMMM dd, yyyy HH:mm");
String dateString = "05/27/2014 23:01";
Date parsedDate = parser.parse(dateString);
String formattedDateString = formatter.format(parsedDate);
System.out.println("Read String '" + dateString + "' as '" + parsedDate + "', formatted as '" + formattedDateString + "'");
When I run this, I get:
Read String '05/27/2014 23:01' as 'Sun Dec 29 23:01:00 EST 2013', formatted as 'December 29, 2013 23:01'
Goal
Convert String to Date with the format you have it in
Output that date as a String in the format you want
Code:
String date = "05/27/2014 23:01";
//convert the String to Date based on its existing format
Date df = new SimpleDateFormat("MM/dd/yyyy HH:mm").parse(date);
System.out.println("date " +df);
//now output the Date as a string in the format you want
SimpleDateFormat dt1 = new SimpleDateFormat("MMMM dd, yyyy HH:mm");
System.out.println(dt1.format(df));
Output:
date Tue May 27 23:01:00 CDT 2014
May 27, 2014 23:01
you can use this >>
String s = sd.format(d);
String s1 = sd1.format(d);
Here Is the full code >>
import java.text.SimpleDateFormat;
import java.util.Date;
public class dt {
public static void main(String[] args) {
// TODO Auto-generated method stub
Date d = new Date();
SimpleDateFormat sd = new SimpleDateFormat("MMMM dd, YYYY");
SimpleDateFormat sd1 = new SimpleDateFormat("HH:mm");
String s = sd.format(d);
String s1 = sd1.format(d);
System.out.println(s +" "+ s1);
}
}
You should have bothered to do a bit of searching before posting. StackOverflow.com has many questions and answers like this already.
But for the sake of posterity, here's some example code using the Joda-Time 2.3 library. Avoid the java.util.Date/Calendar classes bundled with Java as they are badly designed and implemented. In Java 8, continue to use Joda-Time or switch to the new java.time.* classes defined by JSR 310: Date and Time API. Those new classes were inspired by Joda-Time but are entirely re-architected.
Joda-Time has many features aimed at formatting output. Joda-Time offers built-in standard (ISO 8601) formats. Some classes render strings with format and language appropriate to the host computer's locale, or you can specify a locale. And Joda-Time lets you define your own funky formats as well. Searching for "joda" + "format" will get you many examples.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
String input = "05/27/2014" + " " + "23:01";
Parse that string…
// Assuming that string is for UTC/GMT, pass the built-in constant "DateTimeZone.UTC".
// If that string was stored as-is for a specific time zone (NOT a good idea), pass an appropriate DateTimeZone instance.
DateTimeFormatter formatterInput = DateTimeFormat.forPattern( "MM/dd/yyyy HH:mm" ).withZone( DateTimeZone.UTC );
DateTime dateTime = formatterInput.parseDateTime( input );
Ideally you would store the values in an appropriate date-time format in a database. If not possible, then store as a string in ISO 8601 format, set to UTC/GMT (no time zone offset).
// Usually best to write out date-times in ISO 8601 format in the UTC time zone (no time zone offset, 'Z' = Zulu).
String saveThisStringToStorage = dateTime.toDateTime( DateTimeZone.UTC ).toString(); // Convert to UTC if not already in UTC.
Do your business logic and storage in UTC generally. Switch to local time zones and localized formatting only in the user-interface portion of your app.
// Convert to a localized format (string) only as needed in the user-interface, using the user's time zone.
DateTimeFormatter formatterOutput = DateTimeFormat.mediumDateTime().withLocale( Locale.US ).withZone( DateTimeZone.forID( "America/New_York" ) );
String showUserThisString = formatterOutput.print( dateTime );
Dump to console…
System.out.println( "input: " + input );
System.out.println( "dateTime: " + dateTime );
System.out.println( "saveThisStringToStorage: " + saveThisStringToStorage );
System.out.println( "showUserThisString: " + showUserThisString );
When run…
input: 05/27/2014 23:01
dateTime: 2014-05-27T23:01:00.000Z
saveThisStringToStorage: 2014-05-27T23:01:00.000Z
showUserThisString: May 27, 2014 7:01:00 PM

Exception in parsing date format [duplicate]

This question already has answers here:
Date Format JAVA
(5 answers)
Closed 9 years ago.
I have a date in the following format
//input date
Thu Jun 06 2013 00:00:00 GMT+0530 (India Standard Time)
//output date format
I want to change this to "dd-mm-yyyy, hh:mm:ss".
I get the input date format from db. I have to change that into output date format which i will be showing it in a grid.
I tried the following code.
DateFormat outputDate = new SimpleDateFormat("dd-mm-yyyy, hh:mm:ss");
try
{
Date date = outputDate.parse(facade.getDate.toString()); **//getting exception here**
outputDate = new SimpleDateFormat("dd-mm-yyyy, hh:mm:ss");
Date date1 = new SimpleDateFormat("dd-mm-yyyy, hh:mm:ss").parse(outputDate
.format(date));
facade.setDate(date1);
}catch (ParseException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
I am getting
java.text.ParseException: Unparseable date: "2013-06-06 00:00:00.0".
Any help..
"2013-06-06 00:00:00.0" does not match "dd-mm-yyyy, hh:mm:ss" your format should be "dd-MM-yyyy hh:mm:ss" instead
But, looking at your code I'm guessing facade.getDate is actually a java.sql.Timestamp which inherits from java.util.Date so you can directly pass it to the format like so
new SimpleDateFormat("dd-MM-yyyy, hh:mm:ss").format(facade.getDate)
Here's some code which works for me:
import java.text.*;
import java.util.*;
public class Test {
public static void main(String[] args) throws Exception {
String input = "Thu Jun 06 2013 00:00:00 GMT+0530 (India Standard Time)";
DateFormat inputFormat = new SimpleDateFormat("E MMM dd yyyy HH:mm:ss 'GMT'z",
Locale.ENGLISH);
Date date = inputFormat.parse(input);
DateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss",
Locale.ENGLISH);
outputFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String output = outputFormat.format(date);
System.out.println(output);
}
}
Things to consider:
You need to work out your output time zone. Currently I've got it set to UTC, but that may not be what you want.
You really need to take a step back and think things through. You've clearly got two different formats - you're trying to convert from one to the other. So creating three different SimpleDateFormat objects all with the same format is never going to work.
You need to read documentation carefully... in SimpleDateFormat, M means month and m means minute; h uses the 12-hour clock and H uses the 24-hour clock.
This is assuming you actually need to start with a string though. If getDate is already a Date or a Timestamp, you can ignore the first part - just use the output part of the above code. You should avoid unnecessary string conversions wherever possible.
Note that dd-MM-yyyy is a slightly unusual format - are you sure you don't actually want yyyy-MM-dd which is more common (and sortable)?
DateFormat outputDate = new SimpleDateFormat("yyyy-dd-mm hh:mm:ss");
try {
Date date = outputDate.parse("2013-06-06 00:00:00.0");
System.out.println(new SimpleDateFormat("dd-mm-yyyy, hh:mm:ss").format(date));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
works well, line 1 was incorrect. Your SimpleDateFormat.parse needs to be in the exact format of the input date. Then you want to output it in a different format so you make another one and set the format then call SimpleDateFormat.format(date) and I put a println on it.
Fault is here
DateFormat outputDate = new SimpleDateFormat("dd-mm-yyyy, hh:mm:ss");
pattern should be equals to Thu Jun 06 2013 00:00:00 GMT+0530 (India Standard Time). not to your out put strings pattern.
#Test
public void test() throws ParseException {
SimpleDateFormat sdf_org = new SimpleDateFormat("E MMM dd yyyy HH:mm:ss 'GMT'Z", Locale.ENGLISH);
Date d = sdf_org.parse("Thu Jun 06 2013 00:00:00 GMT+0530");
SimpleDateFormat sdf_target = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss.SSS");
System.out.println(sdf_target.format(d));
}
output console : 2013-30-06 03:30:00.000

Categories