Convert String into Date java [duplicate] - java

This question already has answers here:
java does not parse for 'M dd, yyyy' date format
(4 answers)
Closed 7 years ago.
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatter {
public static void main(String[] args) throws ParseException {
String testString = "14 September 11";
DateFormat df = new SimpleDateFormat("dd MMMM yy");
Date newDate = df.parse(testString);
}
}
Tell me, why do I have:
Exception in thread "main" java.text.ParseException: Unparseable date: "14 September 11"
at java.text.DateFormat.parse(DateFormat.java:357)
at com.testtask.ruslan.converter.DateFormatter.main(DateFormatter.java:17)

It will work for English locales, but for others languages it won't. Do not rely on default locale. You always should specify locale explicitly for such conversions:
With Locale.US it passes:
String testString = "14 September 11";
DateFormat df = new SimpleDateFormat("dd MMMM yy", Locale.US);
Date newDate = df.parse(testString);
With new Locale("ru", "RU") it fails:
String testString = "14 September 11";
DateFormat df = new SimpleDateFormat("dd MMMM yy", new Locale("ru", "RU"));
Date newDate = df.parse(testString);

Related

java XMLGregorianCalendar shows different year on conversion [duplicate]

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

Convert Date-Time Stamp [duplicate]

This question already has answers here:
How to parse a date? [duplicate]
(5 answers)
Closed 7 years ago.
I have an XML document that returns the following value for a date-time stamp:
Wed, 18 Feb 2015 22:38:00 +0000
How can I change this (using Java), so I can get this:
Wednesday, February 18, 2015
Have you this date as a string in java?
Try this:
String stringdate = "Wed, 18 Feb 2015 22:38:00 +0000";
//Convert from string to date
DateFormat stringformat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
Date date = stringformat.parse(stringdate);
//Convert from date to string
DateFormat newformat = new SimpleDateFormat("EEEE, MMMM d, yyyy ", Locale.ENGLISH);
System.out.println(newformat.format(date));
With timestamp:
Timestamp d = new Timestamp(System.currentTimeMillis());
//Convert from date to string
DateFormat newformat = new SimpleDateFormat("EEEE, MMMM d, yyyy ", Locale.ENGLISH);
System.out.println(newformat.format(d));
In Java, using SimpleDateFormat, the following should convert the date in the way required by your example.
import java.text.*;
import java.util.*;
public class HelloWorld{
public static void main(String []args) throws ParseException {
String input = "Wed, 18 Feb 2015 22:38:00 +0000";
SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
Date date = sdf.parse(input);
SimpleDateFormat format = new SimpleDateFormat("EEEE, MMMM d, yyyy");
String dateString = format.format(date);
System.out.println(dateString);
}
}

how to format date using SimpleDateFormat

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

Format current date to show day of the week [duplicate]

This question already has answers here:
How to determine day of week by passing specific date?
(28 answers)
Closed 6 years ago.
I want to show the current date in my application like this:
Thu, May 2, 2013
I already have the following code to get the current date
Calendar c = Calendar.getInstance();
Time time = new Time();
time.set(c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.MONTH),
c.get(Calendar.YEAR));
How can I format this Time object to the string I need?
This does what you want
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, yyyy");
String strDate = sdf.format(cal.getTime());
System.out.println("Current date in String Format: " + strDate);
Where strDate can be displayed in your textView or whatever
Maybe you can use it.
This example displays the names of the weekdays in short form with the help of DateFormatSymbols().getWeekdays() method of DateFormatSymbols class.
import java.text.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Date dt = new Date(1000000000000L);
DateFormat[] dtformat = new DateFormat[6];
dtformat[0] = DateFormat.getInstance();
dtformat[1] = DateFormat.getDateInstance();
dtformat[2] = DateFormat.getDateInstance(DateFormat.MEDIUM);
dtformat[3] = DateFormat.getDateInstance(DateFormat.FULL);
dtformat[4] = DateFormat.getDateInstance(DateFormat.LONG);
dtformat[5] = DateFormat.getDateInstance(DateFormat.SHORT);
for(DateFormat dateform : dtformat)
System.out.println(dateform.format(dt));
}
}
output:
9/9/01 7:16 AM
Sep 9, 2001
Sep 9, 2001
Sunday, September 9, 2001
September 9, 2001
9/9/01
Source
Use this
SimpleDateFormat formatter = new SimpleDateFormat("EEE, MMM dd,yyyy");
String formattedDate = formatter.format(new Date(System.currentTimeMillis()));
Log.e("formattedDate",formattedDate);
I will suggest to use java.text.SimpleDateFormat instead.
public static void main(String[] args) {
Date date=new Date();
String format = new SimpleDateFormat("EEE,MMM d,yyyy ").format(date);
System.out.println(format);
}
SimpleDateFormat dateformat= new SimpleDateFormat("dd,MM,yyyy");
String strdate = dateformat.format(new Date(System.currentTimeMillis()));
Oops, I'm a bit slow.

String Date Value Converting

I am converting String to Date format. But it returns "Unparseable date". for example,
String date= "Wednesday, May 15, 2013";
I want to convert this to String like "2013-05-15" How to do that?
Use SimpleDateFormat twice: Once to parse a Date, the other to render it in the desired format:
Date date;
String display = new SimpleDateFormat("yyyy-MM-dd").format(
new SimpleDateFormat("EEEE, MMMM dd, yyyy").parse(date)
);
Your example date is unfortunate, because it uses the only 3-letter month "May", so I can't tell if your month names are all truncated to 3 letters, or if they are the full name. I have assumed months to be the full name, but if they are truncated, change MMMM to MMM in the second format string.
Something like this might help (parse the date string to date object and format it back in the new format):
String dateString = "Wednesday, May 15, 2013";
DateFormat format1 = new SimpleDateFormat("EEEE, MMMM dd, yyyy");
Date date = format1.parse(dateString);
DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
String updatedDateString = format2.format(date);
System.out.println("Updated Date > "+updatedDateString);
In my experiments with this, you need to do something like the below...Refer to the API for understanding how to construct your format strings. http://docs.oracle.com/javase/6/docs/api/index.html?java/text/DateFormat.html
String myDateAsString = "Wednesday, May 15, 2013";
SimpleDateFormat df = new SimpleDateFormat("EEEE, MMM d, yyyy");
Date d = new Date();
try {
d = df.parse(myDateAsString);
} catch (ParseException e1) {
System.out.println("Could not parse...something wrong....");
e1.printStackTrace();
}
df.applyPattern("yyyy-MM-d");
String convertedDate = df.format(d);
System.out.println(convertedDate);
This will be a good approach.
Something like this:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringDate {
public static void main(String[] args) throws ParseException{
String dateString = "Wednesday, May 15, 2013";
DateFormat format1 = new SimpleDateFormat("E, MMM dd, yyyy");
Date date = format1.parse(dateString);
DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
String updatedDateString = format2.format(date);
System.out.println("Updated Date > "+updatedDateString);
}
}

Categories