java date format wrong response - java

I am using this functions to convert date in display format. But return wrong resopnse.
date = converDateFormate("yyyy/MM/dd hh:mm:ss", "MM/dd/yyyy hh:mm a","2013/11/28 12:23:28");
Wrong Response: 11/28/2013 12:23 **AM**
Right Response: 11/28/2013 12:23 **PM** (how can I get this response)
public static String converDateFormate(String oldpattern,
String newPattern, String dateString) throws ParseException {
if (dateString != null) {
SimpleDateFormat sdf = new SimpleDateFormat(oldpattern);
Date testDate = null;
testDate = sdf.parse(dateString);
SimpleDateFormat formatter = new SimpleDateFormat(newPattern);
String newFormat = formatter.format(testDate);
System.out.println("" + newFormat);
return newFormat;
} else {
return "";
}
}

Take a look at here at "Confusion at noon and midnight". If your input is in 24-hours format then you need to use HH:mm:ss in your pattern.

small mistake .
instead of
date = converDateFormate("yyyy/MM/dd hh:mm:ss", "MM/dd/yyyy hh:mm a","2013/11/28 12:23:28");
use this
date = converDateFormate("yyyy/MM/dd HH:mm:ss", "MM/dd/yyyy hh:mm a","2013/11/28 12:23:28");

The old pattern needs to be changed to 24 hours format(HH:mm:ss).
So you have to change the line-
"date = converDateFormate("yyyy/MM/dd hh:mm:ss", "MM/dd/yyyy hh:mm a","2013/11/28 12:23:28");" to
"date = converDateFormate("yyyy/MM/dd HH:mm:ss", "MM/dd/yyyy hh:mm a", "2013/11/28 12:23:28");"

Related

Java Date TIME Format AM/PM Configuration

I am facing problems some while formatting the date:
Date : 11/06/2020 04:14:20
Date Format:dd/MM/yyyy hh:mm:ss a
Exception:
java.text.ParseException: Unparseable date: "11/06/2020 04:14:20"
Following is the code
Blockquote
public String getFormatDate(String inputDate) {
String strDate = "";
try {
DateFormat outputFormat = new SimpleDateFormat("MMMM dd, yyyy hh:mm:ss a");
DateFormat inputFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
Date date1 = inputFormat.parse(inputDate);
strDate = outputFormat.format(date1);
}catch( Exception exe) {
exe.printStackTrace();
logger.error( "[ERROR] getFormatDate:. ", exe );
}
return strDate;
}
Blockquote
Any help would be greatly appeciated.
You can check this code you have to pass the am/pm part too with the date string value as your format is expecting that.
//String date = "11/06/2020 04:14:20";
String date = "11/06/2020 04:14:20 am";
DateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
https://ideone.com/3nibwJ
Use proper date-time objects for your dates and times
For the vast majority of purposes you should not keep your date and time in a string and should not convert your date and time from a string in one format to a string in another format. Keep your date and time in a ZonedDateTime or LocalDateTime object.
When you are required to accept string input, parse that input into a date-time object immediately. I am using and recommending java.time, the modern Java date and time API:
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu HH:mm:ss");
String input = "11/06/2020 04:14:20";
LocalDateTime dateTime = LocalDateTime.parse(input, inputFormatter);
System.out.println(dateTime);
Output so far is:
2020-06-11T04:14:20
Since there is no AM or PM in your string, I have assumed that 04:14:20 was the time of day from 00:00:00 through 23:59:59. If you intended otherwise, you need to explain how.
Only when you need to give string output, format your date and time back into a string of appropriate format:
DateTimeFormatter outputFormatter = DateTimeFormatter
.ofPattern("MMMM dd, yyyy hh:mm:ss a", Locale.ENGLISH);
String output = dateTime.format(outputFormatter);
System.out.println(output);
June 11, 2020 04:14:20 AM
Do provide a locale for the formatter so Java knows which language to use for the month name and the AM/PM indicator.
What went wrong in your code?
Your string has no AM nor PM: 11/06/2020 04:14:20. Yet your format pattern string requires an AM/PM marker in the end. This is what format pattern letter a signifies. So your string wasn’t in the format that you required. This was the reason for the exception that you observed.
Link
Oracle tutorial: Date Time explaining how to use java.time.
Thanks All for your help:
I have changed the source date "11/06/2020 04:14:20" to "06/11/2020 04:14:20 PM", and then after perform follwoing steps, its working for me:
Blockquote
DateFormat inputFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
inputFormat.setTimeZone( TimeZone.getTimeZone("UTC") );
Date dDate = inputFormat.parse( srcDate );
String strDeDate = formatDateToString( dDate, "dd/MM/yyyy hh:mm:ss a", "IST" );
public String formatDateToString(Date date, String format,String timeZone) {
if (date == null) return null;
SimpleDateFormat sdf = new SimpleDateFormat(format);
if (timeZone == null || "".equalsIgnoreCase(timeZone.trim())) {
timeZone = Calendar.getInstance().getTimeZone().getID();
}
sdf.setTimeZone(TimeZone.getTimeZone(timeZone));
return sdf.format(date);
}
Blockquote

i want to convert date fromat: "mm/dd/yyyy hh:mm" to "yyyy-mm-dd hh:mm:ss"

Response from jsp is coming in this format: "mm/dd/yyyy hh:mm", and I want to convert to db format "yyyy-mm-dd hh:mm:ss".
I tried this code :
public java.sql.Date getdateFormat(String datestring) throws ParseException {
String datestr = "";
try {
java.util.Date date = new SimpleDateFormat("mm/dd/yyyy hh:mm a",
Locale.ENGLISH).parse(datestring);
atestr = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(date);
} catch (Exception e) {
e.printStackTrace();
}
return getDateFromString(datestr);
}
public java.sql.Date getDateFromString(String string) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
java.util.Date finalDate = null;
try {
finalDate = sdf.parse(string);
} catch (Exception e) {
e.printStackTrace();
}
return new java.sql.Date(finalDate.getTime());
}
A common mistake in using SimpleDateFormat is skip the documentation and assume that is knows when mm means months and when mm mean minutes. It doesn't. mm only means minutes. If you want months use MM Also only use a if you expect AM/PM and only use hh for 12 hour clocks. I would expect your format should read
MM/dd/yyyy HH:mm
and your output
yyyy-MM-dd HH:mm:ss
BTW You shouldn't need to convert to a String to use JDBC. Using a Date is faster and less error prone.
If all you want is the Date then you do not need to do
atestr=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(date);
simply return the date as this stage.
A date does not have any formatting, it is basically a number.
I would basically do it like this
String dateInString = "20140611";
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date toDate = sdf.parse(dateInString);
sdf = new SimpleDateFormat("yyyy-MM-dd");
String tmpStr = String.format(sdf.format(toDate));
System.out.println(tmpStr);
We can get the date in the following way
DateFormat dfm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date parseDate = dfm.parse(datestring);
Now the parseDate is in the format "yyyy-MM-dd HH:mm:ss"

java.text.parseException:unparsable date

i am getting this error while i am trying to convert a string into date.
unparasable data
Below is my code:-
String str = "hello"
Second is missing at your parse String str. So, to parse it you should not include second format at SimpleDateFormat pattern. Also correct the day and Month format. Look at the declaration of df
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy hh:mm a");//Remove :ss
To know details of pattern, go through this docs.
Edit
String date2 = sdformatter.format(date1);// format method return String.
//Should declare with String
Full Code
String str = "25-Nov-2013 06:00 AM";
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy hh:mm a");//Remove :ss
SimpleDateFormat sdformatter = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss a");
Date date1=null;
try {
date1 = df.parse(str);
} catch (ParseException ex) {
ex.printStackTrace();
}
String date2 = sdformatter.format(date1);
System.out.println(date2);
According to str format you should write your SimpleDateFormat,
(25-Nov-2013 06:00 AM ---> dd-MMM-yyyy hh:mm a) and for
(25-Nov-2013 06:00:30 AM-----> dd-MMM-yyyy hh:mm:ss a)
will work
Try this
long newerdate = new Date().parse("25-Nov-2013 06:30 AM");
java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("dd-MM-yyyy hh:mm a");
String data = df.format(newerdate);
System.out.println(data);

change date format in java

I have string in 'MM/dd/yyyy' format and want to convert it into 'dd-MM-yy'.
e.g. '04/01/2012' should be converted into '01-Apr-12'
Can anyone please suggest how to get this?
SimpleDateFormat currentFormat = new SimpleDateFormat("mm/dd/yyyy");
SimpleDateFormat newFormat = new SimpleDateFormat("dd-mm-yy");
String dateInOldFormat="04/01/2012";
Date temp = currentFormat.parse(dateInOldFormat);
String dateInNewFormat= newFormat.format(temp);
i think things are pretty simple from here on...
You can use the Date class in Java. Parse a string with your format, and then output using a different format.
Below is example of date conversion... For your program, do changes accordingly...
String dateStr = "Thu Jan 19 2012 01:00 PM";
DateFormat readFormat = new SimpleDateFormat( "EEE MMM dd yyyy hh:mm aaa");
DateFormat writeFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = readFormat.parse( dateStr );
} catch ( ParseException e ) {
e.printStackTrace();
}
String formattedDate = "";
if( date != null ) {
formattedDate = writeFormat.format( date );
}
System.out.println(formattedDate);
Output is 2012-01-19 13:00:00
Good Luck

Java Date Formatter

I am getting date format as "YYYY-mm-dd hh:mm" as formatter object.
How can I format the input formatter object to get only "YYYY-mm-dd";?
I am getting date format as
"YYYY-mm-dd hh:mm" as formatter
object. How can i format the input
formatter object to get only
"YYYY-mm-dd";
You can not have date as YYYY-mm-dd it should be yyyy-MM-dd. To get date in yyyy-MM-dd following is the code:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = formatter.format(todaysDate);
Format formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm");
Date date;
try {
date = (Date)((DateFormat) formatter).parse("2011-04-13 05:00");
formatter = new SimpleDateFormat("yyyy-MM-dd");
String s = formatter.format(date);
System.out.println(s);
} catch (ParseException e) {
e.printStackTrace();
}
Use SimpleDateFormat
String myDateString = "2009-04-22 15:51";
SimpleDateFormat inFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(outFormat.format(inFormat.parse(myDateString)));
If you're getting a date in the format "YYYY-mm-dd hh:mm" and you want it as "YYYY-mm-dd" I suggest you just use inputDate.substring(0, 10).
In either way, beware of potential Y10k bugs :)
Following sample formate date as yyyy-MM-dd in Java
Format formatter = new SimpleDateFormat("yyyy-MM-dd");
Calendar now = Calendar.getInstance();
System.out.println("Now: "+formatter.format(now.getTime()) );
Yes, SimpleDateFormat is what you are looking for
http://dlc.sun.com.edgesuite.net/jdk/jdk-api-localizations/jdk-api-zh-cn/builds/latest/html/en/api/java/text/SimpleDateFormat.html
SimpleDateFormat is what you're looking for.
Try this:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = formatter.format(todaysDate);
Use this code:
Date date=new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = formatter.format(date);
System.out.println("formatted time==>" + formattedDate);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Other answers such as the one by user2663609 are correct.
As an alternative, the third-part open-source replacement for the java.util.Date/Calendar classes, Joda-Time, includes a built-in format for your needs.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
String stringIn = "2011-04-07";
// Returns a formatter for a full date as four digit year, two digit month of year, and two digit day of month (yyyy-MM-dd).
DateTimeFormatter formatter = ISODateTimeFormat.date().withZone( DateTimeZone.forID( "Europe/London" ) ).withLocale( Locale.UK );
DateTime dateTime = formatter.parseDateTime( stringIn ).withTimeAtStartOfDay();
String stringOut = formatter.print( dateTime );
Dump to console…
System.out.println( "dateTime: " + dateTime.toString() );
System.out.println( "stringOut: " + stringOut );
When run…
dateTime: 2011-04-07T00:00:00.000+01:00
stringOut: 2011-04-07
This question has so many good answers !! , here comes another one more generic solution
public static String getDateInFormate(String oldFormate , String newFormate , String dateToParse){
//old "yyyy-MM-dd hh:mm"
//new yyyy-MM-dd
//dateTopars 2011-04-13 05:00
String formatedDate="";
Format formatter = new SimpleDateFormat();
Date date;
try {
date = (Date)((DateFormat) formatter).parse(dateToParse);
formatter = new SimpleDateFormat(newFormate);
formatedDate = formatter.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return formatedDate;
}
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String strDate = entry_date;
System.out.println("strDate*************"+strDate);
Date date = null;
try {
date = sdf.parse(strDate);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date yesterday =subtractDay( date);
String requiredDate = df.format(yesterday);
System.out.println("110 days before*******************"+requiredDate);
public static Date subtractDay(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, -110);`enter code here`
return cal.getTime();
}
java.time
I recommend that you use java.time, the modern Java date and time API, for your date and time work.
For parsing input define a formatter:
private static final DateTimeFormatter FORMATTER
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm", Locale.ROOT);
Parse:
String input = "2019-01-21 23:45";
LocalDateTime dateTime = LocalDateTime.parse(input, FORMATTER);
System.out.println(dateTime);
Output so far:
2019-01-21T23:45
Format output:
String output = dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE);
System.out.println(output);
2019-01-21
Tutorial link
Trail: Date Time (The Java™ Tutorials) explaining how to use java.time.

Categories

Resources