Date in String to Date in Date conversion - java

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);
}

Related

converting a date format in java [duplicate]

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");

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.

Extract time from date String

How can I format the "2010-07-14 09:00:02" date string to depict just "9:00"?
Use DateTimeFormatter to convert between a date string and a real LocalDateTime object. with a LocalDateTime as starting point, you can easily apply formatting based on various patterns as definied in the javadoc of the DateTimeFormatter.
String originalString = "2010-07-14 09:00:02";
LocalDateTime dateTime = LocalDateTime.parse(originalString, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
String newString = DateTimeFormatter.ofPattern("H:mm").format(dateTime); // 9:00
In case you're not on Java 8 or newer yet, use SimpleDateFormat to convert between a date string and a real Date object. with a Date as starting point, you can easily apply formatting based on various patterns as definied in the javadoc of the SimpleDateFormat.
String originalString = "2010-07-14 09:00:02";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(originalString);
String newString = new SimpleDateFormat("H:mm").format(date); // 9:00
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2010-07-14 09:00:02");
String time = new SimpleDateFormat("H:mm").format(date);
http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html
A very simple way is to use Formatter (see date time conversions) or more directly String.format as in
String.format("%tR", new Date())
The other answers were good answers when the question was asked. Time moves on, Date and SimpleDateFormat get replaced by newer and better classes and go out of use. In 2017, use the classes in the java.time package:
String timeString = LocalDateTime.parse(dateString, DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"))
.format(DateTimeFormatter.ofPattern("H:mm"));
The result is the desired, 9:00.
I'm assuming your first string is an actual Date object, please correct me if I'm wrong. If so, use the SimpleDateFormat object: http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html. The format string "h:mm" should take care of it.
If you have date in integers, you could use like here:
Date date = new Date();
date.setYear(2010);
date.setMonth(07);
date.setDate(14)
date.setHours(9);
date.setMinutes(0);
date.setSeconds(0);
String time = new SimpleDateFormat("HH:mm:ss").format(date);
let datestring = "2017-02-14 02:16:28"
let formatter = DateFormatter()
formatter.dateStyle = DateFormatter.Style.full
formatter.timeStyle = DateFormatter.Style.full
formatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
let date = formatter.date(from: datestring)
let date2 = formatter.String(from: date)

Java date format real simple

how would you write te date if i have a date and all i want is the month and the day like this (mm/dd) and then turn the month like this July, 08
Let me see if I understood well.
You have a date like "07/08" and you want "July, 08"?
You could try SimpleDateFormat
import java.text.SimpleDateFormat;
import java.text.ParseException;
class Test {
public static void main( String [] args ) throws ParseException {
SimpleDateFormat in = new SimpleDateFormat("MM/dd");
SimpleDateFormat out = new SimpleDateFormat("MMMM, dd");
System.out.println( out.format( in.parse("07/08") ) );
// Verbose
//String input = "07/09";
//Date date = in.parse( input );
//String output = out.format( date );
//System.out.println( output );
}
}
Use:
Format formatter = new SimpleDateFormat("MMMM, dd");
String s = formatter.format(date);
Formatting a Date Using a Custom Format
The SimpleDateFormat is your friend here. If you already have a java.util.Date object, just format it using the desired pattern (refer to the javadoc for details on date and time patterns):
SimpleDateFormat out = new SimpleDateFormat("MMMM, dd");
String s = out.format(date); // date is your existing Date object here
(EDIT: I'm adding some details as the original question is unclear and I may have missed the real goal.
If you have a String representation of a date in a given format (e.g. MM/dd) and want to transform the representation, you'll need 2 SimpleDateFormat as pointed out by others: one to parse the String into a Date and another one to format the Date.
SimpleDateFormat in = new SimpleDateFormat("MM/dd");
Date date = in.parse(dateAsString); // dateAsString is your String representation here
Then use the code snippet seen above to format it.)
the month and the day like this (mm/dd) and then turn the month like this July, 08
So you want to convert MM/dd to MMMM, dd? So you start with a String and you end up with a String? Then you need another SimpleDateFormat instance with the first pattern.
String dateString1 = "07/08";
Date date = new SimpleDateFormat("MM/dd").parse(dateString1);
String dateString2 = new SimpleDateFormat("MMMM, dd").format(date);
System.out.println(dateString2); // July, 08 (monthname depends on locale!).

Categories

Resources