Java - DateFormat not working while converting date [duplicate] - java

This question already has answers here:
Java : Cannot format given Object as a Date
(7 answers)
java.lang.IllegalArgumentException: Cannot format given Object as a Date
(4 answers)
Closed 4 years ago.
I am new to Java. I have been trying to convert a date into format dd-MMM-yy.
But i am getting exception :
Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Date
Below is my code . Please guide.
public class Test {
public static void main(String args[ ]) {
String currentDateString =new String();
DateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy");
DateFormat dateFormatpdfname = new SimpleDateFormat("dd-MMM-yy");
//Date currentDate = new Date();
String dateInString = "Sep 16, 2018";
String dateInString1 = "16-Sep-18";
String currentDateVal=dateFormatpdfname.format(dateInString1);
currentDateString = dateFormat.format(dateInString);
System.out.println(currentDateVal);
System.out.println(currentDateString);
}
}

Uncomment this
//Date currentDate = new Date();
Then,
String currentDateVal=dateFormatpdfname.format(currentDate );
currentDateString = dateFormat.format(currentDate );

Probably i was not passing it as date and that is the reason i was getting error. Below is the correct answer.
public class Test {
public static void main(String args[ ]) throws ParseException {
//Base obj1 = new Base();
// As per overriding rules this should call to class Derive's static
// overridden method. Since static method can not be overridden, it
// calls Base's display()
//Derived.display();
Date myDate = null;
String currentDateString =new String();
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yy");
// DateFormat dateFormatpdfname = new SimpleDateFormat("dd-MMM-yy");
//Date currentDate = new Date();
// String dateInString = "Sep 16, 2018";
String dateInString1 = "16-Sep-18";
myDate = dateFormat.parse(dateInString1);
//String currentDateVal=dateFormatpdfname.format(dateInString1);
currentDateString = dateFormat.format(myDate);
//String releaseDateStr = dateFormat.format(currentDateString);
// System.out.println(currentDateVal);
System.out.println(currentDateString);
}
}

Related

where and how do I initialise a specific date into date object in java [duplicate]

This question already has answers here:
Parse String to Date with Different Format in Java
(10 answers)
Closed 6 years ago.
I am trying to initialise a specific date into date object.How can i do that?I tried using the simpledateformat and parse it in from a string,but it gave me a "declare thrown exception" error when i try to run it.
Date joinDate = new Date();
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String join = "12/05/2012" ;
joinDate = df.parse(join);
This will work fine. But you need to add try-catch block or throws to method
try{
Date joinDate = new Date();
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String join = "12/05/2012" ;
joinDate = df.parse(join);
System.out.println(joinDate);
}catch(ParseException e){
// handle the ParseException
}
Or
public static void main(String[] args) throws ParseException {
Date joinDate = new Date();
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String join = "12/05/2012" ;
joinDate = df.parse(join);
System.out.println(joinDate);
}
public static void main(String[] args) throws ParseException
{
Date joinDate = new Date();
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String join = "12/05/2012" ;
joinDate = df.parse(join);
System.out.println(joinDate);
}

Date difference with joda time

I downloaded joda library and extract joda time to calculate time difference,
Here is my class that calculate date difference: (I'm using Java 1.7)
public class TimeDiffereneceTest {
static String secondDate,firstDate, dateDifference;
public static void main(String[] args) {
firstDate = "2014/07/20";
secondDate = getTodayDate(); // Generate 2014/07/23
DateDifference(firstDate, secondDate);
}
public static String getTodayDate() {
Calendar todayDate = Calendar.getInstance();
SimpleDateFormat simpleFormat = new SimpleDateFormat("YYYY/MM/dd");
String strDate = simpleFormat.format(todayDate.getTime());
return strDate;
}
public static void DateDifference(String firstDate,String nowDate) {
Date d1=null;
Date d2=null;
SimpleDateFormat format = new SimpleDateFormat("YYYY/MM/dd");
try{
d1 = format.parse(firstDate);
d1 = format.parse(nowDate);
DateTime dt1 = new DateTime(d1);
DateTime dt2 = new DateTime(d2);
System.out.println("Day difference is: "+Days.daysBetween(dt1, dt2).getDays()); // 206!
}
catch(Exception e){
e.printStackTrace();
}
}
}
The result should be 3 because today date is 2014/07/23 and first date was "2014/07/20" , But has wrong result (206).
I see some problems with code :
1) new SimpleDateFormat should throw illegal argument becouse of "YYYY" should be"yyyy" (at least for me this works
2) In DateDifference (should be name dateDifference since its a method, not class - naming convenction)
You got
d1 = format.parse(firstDate);
d1 = format.parse(nowDate);
Instead of
d1 = simpleFormat.parse(firstDate);
d2 = simpleFormat.parse(nowDate);
Try using this code, it works for me.
public class TimeDiffereneceTest {
static String secondDate,firstDate, dateDifference;
static SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy/MM/dd");
public static void main(String[] args) {
firstDate = "2014/07/20";
secondDate = getTodayDate(); // Generate 2014/07/23
DateDifference(firstDate, secondDate);
}
public static String getTodayDate() {
Calendar todayDate = Calendar.getInstance();
String strDate = simpleFormat.format(todayDate.getTime());
return strDate;
}
public static void DateDifference(String firstDate,String nowDate) {
Date d1=null;
Date d2=null;
try{
d1 = simpleFormat.parse(firstDate);
d2 = simpleFormat.parse(nowDate);
DateTime dt1 = new DateTime(d1);
DateTime dt2 = new DateTime(d2);
System.out.println("Day difference is: "+Days.daysBetween(dt1, dt2).getDays()); // 206!
}
catch(Exception e){
e.printStackTrace();
}
}
}
Which java version are you using?
In 7, capital Y has a different meaning from y. In 6 Y is not specified so it throws the following exception:
java.lang.IllegalArgumentException: Illegal pattern character 'Y'
Your code has two issues that I can see (apart from the random unused statics).
Y is not the format code for year, y is.
d2 is null, you are parsing both strings into d1.
The following code gives me 4 when run today, '2014/07/24'.
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
String firstDate = "2014/07/20";
String secondDate = format.format(new Date());
int days = Days.daysBetween(new DateTime(format.parse(firstDate)), new DateTime(format.parse(secondDate))).getDays();
System.out.println(days);

how to convert mm/dd/yyyy to yyyy-mm-dd in java [duplicate]

This question already has answers here:
How to convert string "2011-11-29 12:34:25" to date in "dd-MM-yyyy" format in JAVA
(6 answers)
Closed 8 years ago.
i am getting input date as String into mm/dd/yyyy and want to convert it into yyyy-mm-dd
i try out this code
Date Dob = new SimpleDateFormat("yyyy-mm-dd").parse(request.getParameter("dtDOB"));
OK - you've fallen for one of the most common traps with java date formats:
mm is minutes
MM is months
You have parsed months as minutes. Instead, change the pattern to:
Date dob = new SimpleDateFormat("yyyy-MM-dd").parse(...);
Then to output, again make sure you use MM for months.
String str = new SimpleDateFormat("dd-MM-yyyy").format(dob);
It should be
SimpleDateFormat("yyyy-MM-dd")
capital M
For More info refer Oracle Docs
As alternative to parsing you can use regex
s = s.replaceAll("(\\d+)/(\\d+)/(\\d+)", "$3-$2-$1");
Ex -
String dob = "05/02/1989"; //its in MM/dd/yyyy
String newDate = null;
Date dtDob = new Date(dob);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
newDate = sdf.format(dtDob);
} catch (ParseException e) {}
System.out.println(newDate); //Output is 1989-05-02
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class FormatDate {
private SimpleDateFormat inSDF = new SimpleDateFormat("mm/dd/yyyy");
private SimpleDateFormat outSDF = new SimpleDateFormat("yyyy-mm-dd");
public String formatDate(String inDate) {
String outDate = "";
if (inDate != null) {
try {
Date date = inSDF.parse(inDate);
outDate = outSDF.format(date);
} catch (ParseException ex)
System.out.println("Unable to format date: " + inDate + e.getMessage());
e.printStackTrace();
}
}
return outDate;
}
public static void main(String[] args) {
FormatDate fd = new FormatDate();
System.out.println(fd.formatDate("12/10/2013"));
}
}

How do I parse "dd.MM.yyyy G" to ISO-Date in Java? [duplicate]

This question already has answers here:
How to parse date string to Date? [duplicate]
(6 answers)
Closed 9 years ago.
Hey guys I have the date "01.01.1000 AD"(SimpleDate) as String and dd.MM.yyyy G(SimpleFormat) and need to parse it into a Standard ISO-Date in the form 1995-12-31T23:59:59Z (yyyy-MM-dd'T'hh:mm:ss'Z')
my actual code is:
public static String getISODate(String simpleDate, String simpleFormat, String isoFormat) throws ParseException {
Date date;
if (simpleFormat.equals("long")) {
date = new Date(Long.parseLong(simpleDate));
} else {
SimpleDateFormat df = new SimpleDateFormat(simpleFormat);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
// or else testcase
// "1964-02-24" would
// result "1964-02-23"
date = df.parse(simpleDate);
}
return getISODate(date, isoFormat);
}
Does anyone have an idea how do I do that?
Try this:
String string = "01.01.1000 AD";
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy GG");
Date date = dateFormat.parse(string);
The G in the date format stands for era.
See http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
This will hopefully help [tricky with standard jdk, but at least possible - and JSR 310 doesn't support this feature :-( ]:
DateFormat df = new SimpleDateFormat("dd.MM.yyyy GG", Locale.US);
DateFormat iso = new SimpleDateFormat("yyyy-MM-dd");
try {
Date d = df.parse("01.01.1000 AD");
System.out.println(iso.format(d)); // year-of-era => 1000-01-01 (not iso!!!)
// now let us configure gregorian/julian date change right for ISO-8601
GregorianCalendar isoCalendar = new GregorianCalendar();
isoCalendar.setGregorianChange(new Date(Long.MIN_VALUE));
iso.setCalendar(isoCalendar);
System.out.println(iso.format(d)); // proleptic iso year: 1000-01-06
} catch (ParseException ex) {
ex.printStackTrace();
}
Something like this?
String date = "01.01.1000 AD";
SimpleDateFormat parserSDF = new SimpleDateFormat("dd.mm.yyyy GG");
System.out.println(parserSDF.parse(date));
Try it may be help:
public static String getISODate(String simpleDate, String simpleFormat, String isoFormat) throws ParseException {
Date date;
if (simpleFormat.equals("long")) {
date = new Date(Long.parseLong(simpleDate));
} else {
SimpleDateFormat df = new SimpleDateFormat(simpleFormat);
df.setTimeZone(TimeZone.getTimeZone("yyyy-MM-dd'T'HH:mm:ss.SSSZ"));
// or else testcase
// "1964-02-24" would
// result "1964-02-23"
date = df.parse(simpleDate);
}
return getISODate(date, isoFormat);
}

how to convert long date value to mm/dd/yyyy format [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
converting long string to date
I need to convert long date value to mm/dd/yyyy format.my long value is
strDate1="1346524199000"
please help me
Refer Below code which give the date in String form.
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test{
public static void main(String[] args) {
long val = 1346524199000l;
Date date=new Date(val);
SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy");
String dateText = df2.format(date);
System.out.println(dateText);
}
}
Refer below code for formatting date
long strDate1 = 1346524199000;
Date date = new Date(strDate1);
try {
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy");
date = df2.format(format.parse("yourdate");
} catch (java.text.ParseException e) {
e.printStackTrace();
}
Try this example
String[] formats = new String[] {
"yyyy-MM-dd",
"yyyy-MM-dd HH:mm",
"yyyy-MM-dd HH:mmZ",
"yyyy-MM-dd HH:mm:ss.SSSZ",
"yyyy-MM-dd'T'HH:mm:ss.SSSZ",
};
for (String format : formats) {
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
}
and read this http://developer.android.com/reference/java/text/SimpleDateFormat.html
Try something like this:
public class test
{
public static void main(String a[])
{
long tmp = 1346524199000;
Date d = new Date(tmp);
System.out.println(d);
}
}

Categories

Resources