date format in java - java

I want to convert Date in different Format.
For example,
String fromDate = "2011-04-22";
I want to convert this fromDate as "22nd Apr, 2011"
How can I do this?
Thanks in Advance

What you want is a little tricky because of the "nd" in 22nd. Depending on the day it'll need a different suffix. SimpleDateFormat doesn't support formatting like this. You'll have to write some additional code to get it. Here's an example, however it's limited to working in certain locales like US:
SimpleDateFormat fromFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat toFormat = new SimpleDateFormat("d'__' MMM, yyyy");
String fromDate = "2011-04-22";
Date date = fromFormat.parse(fromDate);
String toDate = toFormat.format(date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int day = cal.get(Calendar.DAY_OF_MONTH);
if (day % 10 == 1 && day != 11) {
toDate = toDate.replaceAll("__", "st");
} else if (day % 10 == 2 && day != 12) {
toDate = toDate.replaceAll("__", "nd");
} else if (day % 10 == 3 && day != 13) {
toDate = toDate.replaceAll("__", "rd");
} else {
toDate = toDate.replaceAll("__", "th");
}
System.out.println(toDate);

You can parse the given format using a SimpleDateFormat and then write the 2nd form using a different SimpleDateFormat
SimpleDateFormat from = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat to = new SimpleDateFormat("dd MMM, yyyy");
Date dat = from.parse("2011-04-22");
System.out.println(to.format(dat));
Not sure how to if there is a way to add the 'nd' to '22nd' though.

Following this code to remove ordinal of date. It is running successfully.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class patrn {
private static String deleteOrdinal(String dateString) {
Pattern p1 = Pattern.compile("([0-9]+)(st|nd|rd|th)");
Matcher m = p1.matcher(dateString);
while (m.find()) {
dateString = dateString.replaceAll(Matcher.quoteReplacement(m.group(0)), m.group(1));
}
return dateString;
}
public static void main(String[] args) {
String dateString = "August 21st, 2012";
SimpleDateFormat sdf = new SimpleDateFormat("MMMM dd, yyyy");
Date emp1joinDate = null;
try {
emp1joinDate = sdf.parse(deleteOrdinal(dateString));
} catch (ParseException e) {
e.printStackTrace();
}
}
}

String dateString = "2011-04-22";
SimpleDateFormat format = new SimpleDateFormat("d MMM, yyyy");
try {
Date parsed = format.parse(dateString);
}
catch(ParseException pe) {
System.out.println("ERROR: Cannot parse \"" + dateString + "\"");
}

I would like to point out that format should depend on Locale... Sure, you can do it like this:
String fromDate = "2011-04-22";
DateFormat incomming = new SimpleDateFormat("yyyy-MM-dd");
DateFormat outgoing = DateFormat.getDateInstance(DateFormat.Long, Locale.US);
try {
Date parsed = incomming.parse(fromDate);
String toDate = outgoing.format(parsed);
}
catch (ParseException pe) {
pe.printStackTrace();
}
Of course, instead of Locale.US you need to pass end user's Locale...
BTW. Instead of lousy SimpleDateFormat you might want to use Apache Commons Lang's FastDateFormat. Please also find DateUtils if you are performing a lot of Date-related operations.

Related

How to convert String to Date in java whatever system format is [duplicate]

This question already has answers here:
Parse any date in Java
(6 answers)
Closed 5 years ago.
I'm trying to convert a date string to date object in java regardless of current system date format. Because I want to get my custom date format to store in database. The following is my code and please advice me the way.
public static String dateToString(String date){
if(date.equals("")) return "";
if(date == null || date.length() == 0){
return "";
}
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
try {
Date l_date = format.parse(date);
Calendar calendar = Calendar.getInstance();
calendar.setTime(l_date);
String year = String.format("%04d", calendar.get(Calendar.YEAR));
String month = String.format("%02d", calendar.get(Calendar.MONTH));
String day = String.format("%02d", calendar.get(Calendar.DATE));
return year + month + day;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
For SimpleDateFormat, it can only parse the format I heard coded.
dateToString("16/04/2015");
It can convert for above code. But, when I try with the following format
dateToString("Thursday, April 16, 2015");
I go Unparseable date: "Thursday, April 16, 2015" error.
You're trying to convert a String in EEEE, MMMM dd, yyyy format with the format of dd/MM/yyyy...
Start by using the correct format for the String you trying to convert, the use what ever format you want to convert it back...
SimpleDateFormat from = new SimpleDateFormat("EEEE, MMMM dd, yyyy");
SimpleDateFormat to = new SimpleDateFormat("dd/MM/yyyy");
String value = to.format(from.parse(dateString));
Now you could use something like DateUtils.parseDate(String, String[]) which allows to supply a number of different formats, but is still limited to what you might know.
A better solution would be to store the Date value directly within the database.
You are passing wrong parameter to SimpleDateFormater
Use
SimpleDateFormat format = new SimpleDateFormat("EEEE, MMMM dd, yyyy") instead of SimpleDateFormat to = new SimpleDateFormat("dd/MM/yyyy");
It resolve your Unparseable date issue.
Try to use something like this:
public static String dateToString(String date){
if(date.equals("")) return "";
if(date == null || date.length() == 0){
return "";
}
SimpleDateFormat formatIn = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat formatOut = new SimpleDateFormat("yyyy-dd-MM");
try {
Date l_date = formatIn.parse(date);
String result = formatOut.format(l_date);
return result;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
but if you want to put some data into database you may also use instead String java.sql.Date
something like this:
SimpleDateFormat format = new SimpleDateFormat();
Connection conn = ...
PreparedStatement ps = conn.prepareStatement("...");
long lDate = format.parse(sDate).getTime();
java.sql.Date dDate = new java.sql.Date(lDate);
ps.setDate(1, dDate);

Only accept two or four digit years from users

I have to accept a date from a user via a simple inputText field (JSF 2). I created a Converter so I can validate the date and now I am running into trouble with 1, 3, and 5+ digit years. All dates entered by the user will be either today or in the future (up to a reasonable maximum).
The below solution accepts three different date formats and will correctly handle 2 and 4 digit years (in the former case by using set2DigitYearStart to convert them to 20XX). I am completely stumped how I can handle other wrong dates.
Code
public static void main(String[] args) throws Exception {
String date = "2/3/111"; // This should be rejected!
List<String> datePatterns = new ArrayList<String>();
datePatterns.add("MM-dd-yy");
datePatterns.add("MM.dd.yy");
datePatterns.add("MM/dd/yy");
for (String pattern : datePatterns) {
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
formatter.set2DigitYearStart(new SimpleDateFormat("MM/dd/yyyy").parse("1/1/2000"));
formatter.setLenient(false);
try {
System.out.println(formatter.parse(date));
break;
} catch (ParseException ignore) {
System.out.println("Date format doesn't match pattern: " + pattern);
}
}
}
Examples That Should be Accepted
02/02/02
02/02/2002
Examples That Should be Rejected
02/02/1
02/02/333
02/02/55555
One Approach
Get some theoretical maxDate and yesterday's date, then compare the output. This seems wrong somehow, though...
SimpleDateFormat f4 = new SimpleDateFormat("MM/dd/yyyy");
Date maxDate = f4.parse("01/01/2099");
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
Date minDate = f4.parse(dateFormat.format(cal.getTime()));
Add some specific validation after your parsing is finished to reject any years that are out of range ie getYear() < 1000 and getYear() > 9999
Warning this code is not compiled or tested as I am typing on a tablet.
String dateStr = "2/3/111"; // This should be rejected!
List<String> datePatterns = new ArrayList<String>();
datePatterns.add("MM-dd-yy");
datePatterns.add("MM.dd.yy");
datePatterns.add("MM/dd/yy");
Date date = null;
for (String pattern : datePatterns) {
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
formatter.set2DigitYearStart(new SimpleDateFormat("MM/dd/yyyy").parse("1/1/2000"));
formatter.setLenient(false);
try {
date = dateformatter.parse(dateStr));
break;
} catch (ParseException ignore) {
continue;
}
}
if (date != null) {
Calendar cal = new GregorianCalendar (date);
int year = cal.get(Calendar.YEAR);
if (year() < 1000 || year() > 9999) {
System.out.println("Date format doesn't match pattern: "
+ datePatterns);
}
} else {
System.out.println("Date format doesn't match pattern: "
+ datePatterns);
{

Put character in SimpleDateFormat

I want to validate the code of Date.
Input come from Textbox where user enters it.
and in code it will get calender's date instance and match it.
I want to put character in that SimpleDateFormat.
Code :
SimpleDateFormat formatter = new SimpleDateFormat("dd'ch' MMM, yyyy");
System.out.println("Date is :: " + formatter.format(Calendar.getInstance().getTime()));
String input = "20th Mar, 2014";
if(input.equals(formatter.format(Calendar.getInstance().getTime()))){
System.out.println("Matched");
}else{
System.out.println("Not Matched");
}
I want to put th, rd, st on place of ch in SDF.
means it will take input from user so it can be any date so I want some mechanism so only three will be placed at there.
Anyone knows that how can I do this ?
Help..
UPDATE
SimpleDateFormat formatterth = new SimpleDateFormat("dd'th' MMM, yyyy");
SimpleDateFormat formatterrd = new SimpleDateFormat("dd'rd' MMM, yyyy");
SimpleDateFormat formatternd = new SimpleDateFormat("dd'nd' MMM, yyyy");
SimpleDateFormat formatterst = new SimpleDateFormat("dd'st' MMM, yyyy");
String input = "20th Mar, 2014";
String input1 = "23rd Mar, 2014";
try {
if(input.equals(formatterth.parse(input1)) || input.equals(formatterrd.parse(input1)) || input.equals(formatternd.parse(input1)) || input.equals(formatterst.parse(input1))){
System.out.println("Matched");
}else{
System.out.println("Not Matched");
}
} catch (ParseException e) {
e.printStackTrace();
}
You can't, basically. You need three separate SimpleDateFormat objects:
new SimpleDateFormat("dd'st' MMM, yyyy")
new SimpleDateFormat("dd'nd' MMM, yyyy")
new SimpleDateFormat("dd'th' MMM, yyyy")
... then try parsing with each of them. Note that even this only works with ordinals in English... and it will parse "20st Mar, 2014" which possibly it shouldn't.
Ordinals in date formats are fundamentally a pain, and I haven't personally seen any API which deals with them nicely - partly because they're a pain in localization in general.
You can not do that with one Simple date format but you have to get Day from date check what kind of format you want to use.
Calendar cal = Calendar.getInstance();
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
SimpleDateFormat formatter;
if(dayOfMonth==1||dayOfMonth==21||dayOfMonth==31)
formatter = new SimpleDateFormat("dd'st'MMM, yyyy");
if dayOfMonth like 1,21,31 will use "dd'st' MMM YYYY" and so on.
One other way is try this...
String str="'th'";
String s="dd"+str+"MMM, yyyy";
SimpleDateFormat formatter = new SimpleDateFormat(str);
You can change str="'st'" and str="'rd'"
One more way come to my mind is By the use of method you just need ONE SimpleDate format
public String Method(String str)//pass"''th","'st'" or "'nd'"
{
SimpleDateFormat formatter = new SimpleDateFormat("dd"+str+"MMM, yyyy");
return formatter.format(Calendar.getInstance().getTime()).toString();
}
Try this method(ANS for your UPDATED Question):
public boolean CheckForST(String yourdate)
{
try {
SimpleDateFormat formatter2 = new SimpleDateFormat("dd'st' MMM, yyyy");
formatter2.parseObject(yourdate);
return true;
} catch (ParseException e) {
return false;
}
}
Which is only implemented for 'st' you can do the same for 'rd' or 'nd'

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 to create Date object from String value

When running through the below code I am getting an UNPARSABLE DATE EXCEPTION.
How do I fix this?
package dateWork;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateCreation {
/**
* #param args
*/
public static void main(String[] args) {
String startDateString = "2013-03-26";
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
Date startDate=null;
String newDateString = null;
try
{
startDate = df.parse(startDateString);
newDateString = df.format(startDate);
System.out.println(startDate);
} catch (ParseException e)
{
e.printStackTrace();
}
}
}
You used wrong dateformat for month, also you should use the same delimiter as in your date.
If you date string is of format "2013/01/03"
use the same delimiter / for the pattern "yyyy/MM/dd"
If your date string is of format "2013-01-03"
use the same delimiter '-' in your pattern "yyyy-MM-dd"
DateFormat df = new SimpleDateFormat("yyyy/mm/dd");
should be
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
From SimpleDateFormat Doc
MM---> month in an year
mm---> minutes in hour
MM instead of mm
- instead of /
ie yyyy-MM-dd as you are using - in date string
String startDateString = "2013-03-26";
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
you are using different pattern than what you are parsing.
either initialize this as DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
or this as String startDateString = "2013/03/26";
also look this article
pass same format string in constructor of SimpleDateFormat("yyyy-mm-dd")
as your string date is "2013-03-26"
if your date is "2013/03/26" use
SimpleDateFormat("yyyy/mm/dd")

Categories

Resources