converting a date format in java [duplicate] - java

This question already has answers here:
Parsing ISO-8601 DateTime with offset with colon in Java
(4 answers)
Closed 3 years ago.
I have a date value: - 2019-09-30T00:00:00.000+05:30
I want to convert into the format - dd MMM yyyy
I have the code:
public static String parseDateAndTimeStringCust(String datestring) {
if(datestring.length()>=10){
SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
String fDate = new SimpleDateFormat("dd MMM yyyy").format(dateFormat2.parse(datestring));
return fDate;
} catch (ParseException ex) {
ex.printStackTrace();
}
}
return datestring;
}
Analysis:
My dateFormat2 I am using is wrong
Question:
What is the correct data format i have to use so that I can get the
result in the format dd MMM yyyy
What is the proper reference I can use in future to build such date
formats

You should use classes from the java.time package.
This is what you're looking for.
String str = "2019-09-30T00:00:00.000+05:30";
OffsetDateTime dt = OffsetDateTime.parse(str);
String out = dt.format(DateTimeFormatter.ofPattern("dd MMM yyyy"));
System.out.println(out);
Note that the actual output depends on your locale, but then you could supply the Locale as the second argument to DateTimeFormatter.ofPattern.
Also note that the single-argument version of OffsetDateTime.parse implies the ISO_OFFSET_DATE_TIME format.
Furthermore, whether the actual output of abovementioned method is accurate, depends on how you want to handle the timezone offset, i.e. whether you want to convert it to UTC or ignore it. For instance, the timestamp 2019-09-30T00:00:00.000+05:30 actually falls on the 29th of September if converted to UTC (the time is then 2019-09-29T18:30:00.000Z).
DateTimeFormatter
The documentation of the DateTimeFormatter class contains detailed information about the formatting symbols and how they are parsed. There are many predefined formats for well-known and commonly used patterns, for example ISO_OFFSET_DATE_TIME conforming with the ISO 8601 standard.

public static String parseDateAndTimeStringCust(String datestring) {
Date dataFormated = null;
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
try {
dataFormated = dateFormat.parse(datestring);
} catch (ParseException ex) {
ex.printStackTrace();
}
return dataFormated.toString();
}

Try changing following line:
SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
To:
SimpleDateFormat dateFormat2 = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");

Related

Date in String to Date in Date conversion

I'm having date in String format as "2019-10-30 12:17:47". I want to convert this to an instance of Date along with the time so that I can compare two date obejcts.
This is what I've tried:
String dateString = "2019-10-30 12:17:47" //Date in String format
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss"); //sdf
Date d1 = format.parse(dateString);
But here I'm getting exception as "Unparseble date exception".
Kindly help...
What went wrong in your code?
In your format pattern string, yyyy-MM-dd HH-mm-ss, you have got two spaces between the date and the time. Since your date string, 2019-10-30 12:17:47, has got only one space there, your formatter objects by throwing the exception. This was also what Tim Biegeleisen said in a comment. The comment by deHaar is true too: The hyphens between hour, minute and second don’t match the colons in your date string either.
What to do instead?
See the good answer by deHaar
You should really switch to java.time (as already suggested in one of the comments below your question). It isn't more difficult than the outdated temporal classes from java.util but less error-prone and more powerful concerning offsets, time zones, daylight saving time and the multitude of different calendars the world has.
See this little example:
public static void main(String[] args) {
String dateString = "2019-10-30 12:17:47";
// define your pattern, should match the one of the String ;-)
String datePattern = "yyyy-MM-dd HH:mm:ss";
// parse the datetime using the pattern
LocalDateTime ldt = LocalDateTime.parse(dateString,
DateTimeFormatter.ofPattern(datePattern));
// print it using a different (here a built-in) formatting pattern
System.out.println(ldt.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
// or you just use the one defined by you
System.out.println(ldt.format(DateTimeFormatter.ofPattern(datePattern)));
// or you define another one for the output
System.out.println(ldt.format(DateTimeFormatter.ofPattern("MMM dd yyyy HH-mm-ss")));
}
The output on my system looks like this:
2019-10-30T12:17:47
2019-10-30 12:17:47
Okt 30 2019 12-17-47
The date in string you want to format does not match the formatter. See more detail here,
https://docs.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html
#Test
public void test2() {
String dateString = "2019-10-30 12:17:47"; //Date in String format
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //sdf
try {
Date d1 = format.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
}
There are two ways to do it
first is your way
String dateString = "2019-10-30 12:17:47"; // Date in String format
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // sdf
Date d1 = format.parse(dateString
second is my way (Local date)
LocalDate resultDate = dateFormat("2019-10-30 12:17:47");
System.out.println(resultDate);
public static LocalDate dateFormat(String textTypeDateTime) {
final DateTimeFormatter dateTimetextFormatter =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
return LocalDate.parse(textTypeDateTime, dateTimetextFormatter);
}

Java Date Parsing from string

I'm trying to parse a String into Data, I create the DataParser, in according to date format, the code I wrote is this:
String date_s = "04-May-2017 17:28:27";
DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
Date date;
try {
date = formatter.parse(date_s);
System.out.println(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
When I execute this, I got always an exception
java.text.ParseException: Unparseable date: "04-May-2017 17:28:27"
I don't understand why the data is not parsed, someone can help me?
This thread of answers would not be complete without the modern solution. These days you should no longer use Date and SimpleDateFormat, but switch over to the newer date and time classes:
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("dd-MMM-yyyy HH:mm:ss", Locale.ENGLISH);
LocalDateTime dateTime;
try {
dateTime = LocalDateTime.parse(date_s, formatter);
System.out.println(dateTime);
} catch (DateTimeParseException e) {
System.err.println(e);
}
This prints
2017-05-04T17:28:27
(LocalDateTime.toString() returns ISO 8601 format) If leaving out Locale.ENGLISH, on my computer I get
Text '04-May-2017 17:28:27' could not be parsed at index 3
Index 3 is where it say May, so the message is somewhat helpful.
LocalDateTime and DateTimeFormatter were introduced in Java 8, but have also been backported to Java 6 and 7.
the string you want to parse is local dependent (the word May is English), so the jvm is not able to infer that may is the month of may in English
define the formatter using the constructor qith the locale.
DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss",Locale.ENGLISH);
You need another constructor with a Locale that supports MMM (May)
DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss",Locale.US)
or using standard format dd-MM-yyyy with month digits.
(Sorry, in the meantime the answer was already posted)

Java - SimpleDateFormat parse from String issue

I'm trying to parse the following string to a Date object:
String str = "04/15/2014 10:30:24"
I'm using SimpleDateFormat :
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
java.util.Date orderDate = sdf.parse(str);
java.sql.Date orderSqlDate = new java.sql.Date(orderDate.getTime());
but orderSqlDate always returned: 04/15/2014 00:00:00
how to use SimpleDateFormat in java exactly?
The java.sql.Date javadoc states
To conform with the definition of SQL DATE, the millisecond values
wrapped by a java.sql.Date instance must be 'normalized' by setting
the hours, minutes, seconds, and milliseconds to zero in the
particular time zone with which the instance is associated.
If you're going to use java.sql.Date, there's no way around this.
You are also doing correct.
But to get the result in the format you want, you need to use .format("/your format/") method after parsing the string.
String date = "15/12/2014 10:42:24";
SimpleDateFormat dateParser = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date parseDate = dateParser.parse(date);
formatter.format(parseDate) // this will change format of date as you want.
I don't think the way you parse is wrong. Are you sure you print orderDate right ?
The following code demonstrates both parsing and formatting (printing).
public static void main(String[] args) {
String format = "MM/dd/yyyy HH:mm:ss";
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date orderDate = new SimpleDateFormat(format).parse("04/15/2014 10:30:24");
System.out.println(sdf.format(orderDate));
} catch (Exception e) {
e.printStackTrace();
}
}
Provide Locale in the SimpleDateFormat constructor, otherwise parsing might be dependant on your local settings:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.ROOT);

Date formatting exception unparseable date

I am trying to format dates entered by my application user using SimpleDateFormat but I always get an error:
01/28/2014java.text.ParseException: Unparseable date: "01/28/2014"
The code I am using to format the date is as follows:
Date rDate, dDate;
String Date1 = request.getParameter("Date1");
String Date2 = request.getParameter("Date2");
//Here the date get display for example as 01/29/2014 (i.e. MM/DD/YYYY)
System.out.println("Date1:: "+ Date1);
System.out.println("Date2:: "+ Date2);
SimpleDateFormat parseRDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat parseDDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
//#########Crashes in the next two lines#########...
rDate = (Date)parseRDate.parse(Date1);
dDate = (Date)parseDDate.parse(Date2);
} catch (ParseException e) {
e.printStackTrace();
}
Can someone please help me by telling me what I am doing wrong here?
Thanks for your time
You need to match the DateFormat pattern to your input String
SimpleDateFormat parseRDate = new SimpleDateFormat("MM/dd/yyyy");
Any idea how I can convert the format from MM/dd/YYYY to yyyy-MM-dd HH:mm:ss?
All you need to do is use a separate SimpleDateFormat instance for formatting
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(output.format(date1));
As you say, Date1 is of the form MM/dd/yyyy... but you're trying to parse it with a format of yyyy-MM-dd HH:mm:ss.
The pattern you parse to the SimpleDateFormat constructor has to match the format of the data itself. (What did you think you were specifying in the constructor?)
Note that the code you've provided isn't doing and formatting at all - just parsing.
You should also work out which time zone you're interested in, and which Locale. Personally I think it's clearer to specify both of those explicitly - even if you want the system default ones.
(If you're doing any significant amount of date/time work, you should also consider using Joda Time, which is a much more pleasant date/time API. I'd also consider more useful exception handling, and following Java naming conventions...)
You specify the format yyyy-MM-dd HH:mm:ss in the constructor and then accept a completely different format (MM/dd/yyyy) as input. You need to make the actual format match the expected format.
Examine the following (for comparison):
Date rDate, dDate;
SimpleDateFormat parseRDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat parseDDate = new SimpleDateFormat("MM/dd/yyyy");
try {
rDate = (Date)parseRDate.parse("2014-01-28 12:22:22");
dDate = (Date)parseDDate.parse("01/28/2014");
} catch (ParseException e) {
e.printStackTrace();
}
The string passed to the constructor is what tells SimpleDateFormat how to read the input you give it later.

DateTime formatter

I am developing an application and I am stuck in converting string like 01/01/2037 01:00:00 AM
to Date
I used
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh.mm.ss.S aa")
Date d = dateFormat.parse(dateString);
but I get an error, any help will be appreciated.
you are converting this 01/01/2037 01:00:00 AM
therefore use
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss aa")
(more info in [documentation])1
then
Date date = dateFormat.parse("01/01/2037 01:00:00 AM");
keep in mind you have to wrap a try-catch around the parse method.
The problem is that the format you declared is nothing like the String you are trying to parse:
your String uses / to separate day, month, year while in your formatter you use -
your string separates hours with a dot, while in the formatter you use :
you do not have milliseconds in your string while you declared them in the formatter.
The following code should work:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh.mm.ss.S aa");
try {
Date date = dateFormat.parse("01-01-2037 01.00.00.000 AM");
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}

Categories

Resources