This question already has answers here:
How to convert String object to Date object? [duplicate]
(8 answers)
Closed 9 years ago.
How can this 11/03/2009-20:06:16 to a Date object so I can compare two dates. I keep getting java.lang.IllegalArgumentException: Cannot format given Object as a Date error if I use below implementation.. I need the output to be date object with format Tue Jul 14 01:32:31 2009
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Dateaf {
/**
* #param args
* #throws ParseException
*/
public static void main(String[] args) throws ParseException {
// TODO Auto-generated method stub
String text = "11/03/2009-20:06:16";
SimpleDateFormat dateParser = new SimpleDateFormat("MM/dd/yyyy-hh:mm:ss");
Date date = dateParser.parse(text);
System.out.println(date);
}
}
sdf.format() takes a Date object and returns a String. You are passing a String to it.
You are very close, just drop the call to format:
Date date = sdf.parse(text);
So:
String text = "11-03-2009 20:06:16";
SimpleDateFormat dateParser = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
//^^ capital H for 24 hour
Date date = dateParser.parse(text);
And to print (from your comment in the format "Tue Jul 14 01:32:31 2009"):
SimpleDateFormat dateFormatter = new SimpleDateFormat("EE MM dd HH:mm:ss yyyy");
System.out.println(dateFormatter.format(date));
The SimpleDateFormat javadoc is an excellent reference for formats.
EDIT
After OP's edits here is a full example
public static void main(String[] args) throws ParseException {
final String text = "11/03/2009-20:06:16";
final SimpleDateFormat dateParser = new SimpleDateFormat("MM/dd/yyyy-HH:mm:ss");
final Date date = dateParser.parse(text);
final SimpleDateFormat dateFormatter = new SimpleDateFormat("EE MMM dd HH:mm:ss yyyy");
System.out.println(dateFormatter.format(date));
}
Output:
Tue Nov 03 20:06:16 2009
Java has the text package which gives us the predefined class text
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) throws Exception{
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date today = df.parse("20/12/2005");
System.out.println("Today = " + df.format(today));
}
}
There is another way of doing this
String date = "2000-11-01";
java.sql.Date javaSqlDate = java.sql.Date.valueOf(date);
Related
I’m trying to calculate the number of days between 2 dates. When I run this, it throws the catch (ParseException ex).
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) {
String date1 = "11/11/2020";
String date2 = "13/11/2020";
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy");
Date date_1 = dateFormat.parse(date1);
Date date_2 = dateFormat.parse(date2);
System.out.println(date_1);
System.out.println(date_2);
long numberOfDays = date_2.getTime() - date_1.getTime();
numberOfDays = TimeUnit.DAYS.convert(numberOfDays, TimeUnit.MILLISECONDS);
System.out.println(numberOfDays);
}
catch (ParseException ex)
{
System.out.println("error");
}
}
}
other than the catch, there are no errors, so I’m kind of lost.
Don't use Date. Try this.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String date1 = "11/11/2020";
String date2 = "13/11/2020";
LocalDate d1 = LocalDate.parse(date1,dtf);
LocalDate d2 = LocalDate.parse(date2,dtf);
long ndays = d1.datesUntil(d2).count();
System.out.println(ndays);
If you had printed the catched exception:
System.out.println("error: " + ex.getLocalizedMessage());
You would have seen:
error: Unparseable date: "11/11/2020"
The problem is in:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy");
change it to:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Since the provided dates are in that format.
If Java 8 is an option I'd recommend using the Time API.
Example:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class Main
{
public static void main(String[] args) {
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String date1 = "11/11/2020";
String date2 = "13/11/2020";
LocalDate firstDate = LocalDate.parse(date1, format);
LocalDate secondDate = LocalDate.parse(date2, format);
long days = ChronoUnit.DAYS.between(firstDate, secondDate);
System.out.println("Days between: " + days);
}
}
Just change this :
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy");
to that :
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
The date you are trying to parse 11/11/2020 does not match the date format you are trying to use dd-mm-yyyy
You can resolve problems like that on your own by printing out the stack trace inside catch :
ex.printStackTrace();
First, you have different formats in input dates and defined format. Therefore, you're getting a parsing exception.
Secondly, We can java.time.Duration class in Java8 for such calculation. Example:
public static void main(String[] args) throws ParseException {
String date1 = "11/11/2020";
String date2 = "13/11/2020";
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Duration duration = Duration.between(format.parse(date1).toInstant(), format.parse(date2).toInstant());
System.out.println("Days between: " + duration.toDays());
}
Your pattern is incorrect.
You use:
new SimpleDateFormat("dd-mm-yyyy");
but you need use:
new SimpleDateFormat("dd/mm/yyyy");
because yours date's have "/" instead of "-"
This question already has answers here:
Why does sdf.format(date) converts 2018-12-30 to 2019-12-30 in java? [duplicate]
(3 answers)
Java SimpleDateFormat returning wrong value in Date object
(1 answer)
Y returns 2012 while y returns 2011 in SimpleDateFormat
(5 answers)
Closed 3 years ago.
Simple test case below is giving results different than expected.
import javax.xml.datatype.XMLGregorianCalendar;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Main {
public static void main(String[] args) {
XMLGregorianCalendar xmlDate = new XMLGregorianCalendarImpl();
xmlDate.setMonth(12);
xmlDate.setDay(31);
xmlDate.setYear(2019);
xmlDate.setHour(0);
xmlDate.setMinute(0);
xmlDate.setSecond(0);
Calendar calendar = xmlDate.toGregorianCalendar();
SimpleDateFormat formatter = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
Date dt = calendar.getTime();
String ds1 = dt.toString();
System.out.println("ds1 = " + ds1);
String dateString = formatter.format(calendar.getTime());
System.out.println("dateString = " + dateString );
}
}
I cannot figure out why the year component of dateString is showing as 2020 instead of 2019.
ds1 = Tue Dec 31 00:00:00 EST 2019
dateString = 2020-12-31 00:00:00
Please change your code to
import javax.xml.datatype.XMLGregorianCalendar;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Main {
public static void main(String[] args) {
XMLGregorianCalendar xmlDate = new XMLGregorianCalendarImpl();
xmlDate.setMonth(12);
xmlDate.setDay(31);
xmlDate.setYear(2019);
xmlDate.setHour(0);
xmlDate.setMinute(0);
xmlDate.setSecond(0);
Calendar calendar = xmlDate.toGregorianCalendar();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dt = calendar.getTime();
String ds1 = dt.toString();
System.out.println("ds1 = " + ds1);
String dateString = formatter.format(calendar.getTime());
System.out.println("dateString = " + dateString );
}
}
As YYYY represents year of the week and yyyy represents calendar year in simple date format.
More explanation here: Java SimpleDateFormat shifts Date by one year
This question already has answers here:
want current date and time in "dd/MM/yyyy HH:mm:ss.SS" format
(11 answers)
return date type with format in java [duplicate]
(1 answer)
Closed 4 years ago.
I want to take a date value as String in the format yyyy-MM-dd and return a jabva util date in the same format.
for this I am using below code , but the result is coming as "Wed Sep 18 00:00:00 CEST 2013"
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String strdate = "2013-09-18";
Date utilDate = sdf.parse(strdate);
System.out.println(utilDate);
Do i need to consider the locale also ?
Please help to achieve this.
Thanks in advance
Please try below code.
You also have to format your simpleDateFormat object and pass utilDate object inside it to create formatted date as specified by you.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTest {
public static void main(String[] args) throws ParseException{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String strdate = "2013-09-18";
Date utilDate = sdf.parse(strdate);
String date=sdf.format(utilDate );
System.out.println(date);
}
}
We can also implement through Java8 like below:
import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class DateTest {
public static void main(String[] args) throws ParseException{
String strdate = "2013-09-18";
DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate date = LocalDate.parse(strdate, formatter);
System.out.println(date.format(formatter));
}
}
or you can also use only LocalDate to change in java util like below.
import java.time.LocalDate;
public class TestCircle {
public static void main(String args[]){
String strdate = "2013-09-18";
LocalDate date = LocalDate.parse(strdate);
System.out.println(date);
}
}
I cannot format a date.
dateFormat.format() accepts a Date as argument. So I created a new Date()
It says the below Date() method is deprecated, and I get the below exception while running.
exception:
Exception in thread "main" java.lang.IllegalArgumentException at
java.util.Date.parse(Date.java:598)
public class MyDate {
public static void main(String[] args) {
Date date = new Date("2012-02-16T00:00:00.000-0500");
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd-MMM-yyyy HH:mm:ss");
String stringDate = dateFormat.format(date);
System.out.println(stringDate); // how do I test this conversion??
}
}
My database has date of the format - 2012-02-16T00:00:00.000-0500
I need to convert it to string of the format : dd-MMM-yyyy HH:mm:ss
I'm using Java6
Thanks to #Andy Brown. In addition to what Andy Brown has answered, I'm posting the complete snippet
Complete Solution:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SampleDate {
public static void main(String[] args) throws ParseException {
DateFormat parseFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date date = parseFormat.parse("2012-03-16T00:00:00.000-0500");
String strDate = parseFormat.format(date);
System.out.println(strDate);
// if you get date of type 'java.sql.Date' directly from database cursor like
//rs.getDate("created_date"), just pass it directly to format()
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd-MMM-yyyy HH:mm:ss");
String stringDate = dateFormat.format(date);
System.out.println(stringDate);
}
}
/*
Output:
2012-03-16T01:00:00.000-0400
16-Mar-2012 01:00:00
*/
you can also convert java.util.Date to java.sql.Date like this,
String dateString = "03-11-2012";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
java.util.Date date = dateFormat.parse(dateString);
java.sql.Date sqlDate = new Date(date.getTime());
// set the input param type as OracleTypes.DATE and pass the input param date as sqlDate
If you want to read in the date "2012-02-16T00:00:00.000-0500" you should probably use a SimpleDateFormat to parse it like so:
DateFormat parseFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date date = parseFormat.parse("2012-02-16T00:00:00.000-0500");
Along with the rest of your code this writes:
16-Feb-2012 05:00:00
The parse format pattern letters are listed in the SimpleDateFormat documentation. The T is escaped with apostrophes.
This answer assumes Java 7, or you would be using the new date & time API from Java 8
Hi for some of the requirement i need to convert the string representation of date(with no format) to date object and convert back to string(with a specific format)
This is what i tried so far, the output is not coming as expected and it's printing something like 08140009 - Any idea what is this
And please provide any suggestions.
MY code is :
public String getDateBackToCST(String createDate){
SimpleDateFormat dateFormatter = new SimpleDateFormat("MMddyyyy");
TimeZone obj = TimeZone.getTimeZone("CST");
dateFormatter.setTimeZone(obj);
Date createdDate = null;
try {
createdDate = dateFormatter.parse(createDate);
} catch (ParseException e) {
e.printStackTrace();
}
return dateFormatter.format(createdDate);
}
You need to specific proper flags for SimpleDateFormat. You have 2 options to specify timezone z and Z and to specify day name use E like this
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class Main {
public static void main(String[] args) throws ParseException {
String date = "Sat Sep 20 23:39:04 IST 2014 ";
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd hh:mm:ss z yyyy");
System.out.println(sdf.parse(date));
}
}