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
Related
This question already has answers here:
Comparing two times in android
(4 answers)
12:xx shown as 00:xx in SimpleDateFormat.format("hh:mm:ss")
(1 answer)
Closed 3 years ago.
I am trying to use Date objects and calculate time differences for an android app. But I face a problem when time is in '12:00'. I mean when I input date as 12:12:00 Java AM/PM formatter returns 12:12:00AM but it should be 12:12:00PM.
I can't find any way to solve it.
Date date = new Date();
String stringDate = "2019-09-13 12:12:00";
SimpleDateFormat formatter6=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date6 = formatter6.parse(stringDate);
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss a");
System.out.println(sdf.format(date6));
It returns 12:12:00 AM
but it should be 12:12:00 PM for correct calculations
In Line:
SimpleDateFormat formatter6=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
The hh makes sure that hours are parsed as AM/PM values b/w 1-12. To get the desired result, you can use HH marker which parses hour values between 0-23. So, the code should be:
SimpleDateFormat formatter6=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Use DateTimeFormatter and LocalDateTime
String stringDate = "2019-09-13 12:12:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime date = LocalDateTime.parse(stringDate, formatter);
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("hh:mm:ss a");
System.out.println(formatter2.format(date));
You might also want to set a Locale for your second formatter depending on where you live.
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("hh:mm:ss a", Locale.US);
System.out.println(formatter2.format(date));
12:12:00 PM
Pass the AM/PM in the time
Date date = new Date();
String stringDate = "2019-09-13 12:12:00 PM";
SimpleDateFormat formatter6 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
Date date6 = formatter6.parse(stringDate);
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss a");
System.out.println(sdf.format(date6));
Try to do it the modern way, that is using java.time:
String stringDate = "2019-09-13 12:12:00";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime datetime = LocalDateTime.parse(stringDate, dtf);
DateTimeFormatter dtfA = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss a");
System.out.println(datetime.format(dtfA));
// receive the time part and format it
LocalTime timePart = datetime.toLocalTime();
DateTimeFormatter tf = DateTimeFormatter.ofPattern("hh:mm:ss a");
System.out.println(timePart.format(tf));
This outputs
2019-09-13 12:12:00 PM
12:12:00 PM
on my system.
Note that your pattern String used for parsing is wrong since you are not using capital "H" for the hours of day, but "h" instead. That will definitely not work (correctly).
Two solutions,
1.
Date date = new Date();
String stringDate = "2019-09-13 12:12:00 PM";
SimpleDateFormat formatter6=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
2.
Date date = new Date();
String stringDate = "2019-09-13 12:12:00";
SimpleDateFormat formatter6=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
If you are using java 8 or above then you should definitely use LocalDateTime and DateTimeFormatter makes it way easier to work with date times.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss a");
String am = LocalDateTime.now().format(formatter);
String pm = LocalDateTime.now().plusHours(2).format(formatter);
System.out.println(am);
System.out.println(pm);
Now I am assuming that I run this code during am hours just 2 hours before it changes to pm you can also try out #Joakim Danielson answer which should not be dependent on when it is run.
checkout the documentation for LocalDateTime and DateTimeFormatter
"Mar 10, 2016 6:30:00 PM" This is my date and I want to convert this into "10 Mar 2016". Can I use SimpleDateFormat in android. I am not getting the exact pattern to convert it. Please help and thanks in advance
String date="Mar 10, 2016 6:30:00 PM";
SimpleDateFormat spf=new SimpleDateFormat("Some Pattern for above date");
Date newDate=spf.format(date);
spf= new SimpleDateFormat("dd MMM yyyy");
String date = spf.format(newDate);
Will this steps work? If yes, can someone please give me a pattern of that format? Thanks in advance.
This is modified code that you should use:
String date="Mar 10, 2016 6:30:00 PM";
SimpleDateFormat spf=new SimpleDateFormat("MMM dd, yyyy hh:mm:ss aaa");
Date newDate=spf.parse(date);
spf= new SimpleDateFormat("dd MMM yyyy");
date = spf.format(newDate);
System.out.println(date);
Use hh for hours in order to get correct time.
Java 8 and later
Java 8 introduced new classes for time manipulation, so use following code in such cases:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd, yyyy h:mm:ss a");
LocalDateTime dateTime = LocalDateTime.parse(date, formatter);
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("dd MMM yyyy");
System.out.println(dateTime.format(formatter2));
Use h for hour format, since in this case hour has only one digit.
conversion from string to date and date to string
String deliveryDate="2018-09-04";
SimpleDateFormat dateFormatprev = new SimpleDateFormat("yyyy-MM-dd");
Date d = dateFormatprev.parse(deliveryDate);
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE dd MMM yyyy");
String changedDate = dateFormat.format(d);
You can use following method for this problem. We simply need to pass Current date format, required date format and Date String.
private String changeDateFormat(String currentFormat,String requiredFormat,String dateString){
String result="";
if (Strings.isNullOrEmpty(dateString)){
return result;
}
SimpleDateFormat formatterOld = new SimpleDateFormat(currentFormat, Locale.getDefault());
SimpleDateFormat formatterNew = new SimpleDateFormat(requiredFormat, Locale.getDefault());
Date date=null;
try {
date = formatterOld.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
if (date != null) {
result = formatterNew.format(date);
}
return result;
}
This method will return Date String in format you require.
In your case method call will be:
String date = changeDateFormat("MMM dd, yyyy hh:mm:ss a","dd MMM yyyy","Mar 10, 2016 6:30:00 PM");
You should parse() the String into Date and then format it into the desired format. You can use MMM dd, yyyy HH:mm:ss a format to parse the given String.
Here is the code snippet:
public static void main (String[] args) throws Exception
{
String date = "Mar 10, 2016 6:30:00 PM";
SimpleDateFormat spf = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a");
Date newDate = spf.parse(date);
spf = new SimpleDateFormat("dd MMM yyyy");
String newDateString = spf.format(newDate);
System.out.println(newDateString);
}
Output:
10 Mar 2016
For the sake of completeness, here is the modern version. This is for anyone reading this who either uses Java 8 or later or is happy with a (good and futureproof) external library.
String date = "Mar 10, 2016 6:30:00 PM";
DateTimeFormatter parseFormatter
= DateTimeFormatter.ofPattern("MMM d, uuuu h:mm:ss a", Locale.ENGLISH);
DateTimeFormatter newFormatter
= DateTimeFormatter.ofPattern("d MMM uuuu", Locale.ENGLISH);
date = LocalDateTime.parse(date, parseFormatter).format(newFormatter);
System.out.println(date);
This prints the desired
10 Mar 2016
Please note the use of explicit locale for both DateTimeFormatter objects. “Mar” and “PM” both are in English, so neither the parsing nor the formatting will work unless some English-speaking locale is used. By giving it explicitly we are making the code robust enough to behave as expected also on computers and JVMs with other default locales.
To use the above on Android, use ThreeTenABP, please see How to use ThreeTenABP in Android Project. On other Java 6 and 7 use ThreeTen Backport.
You need to use SimpleDateFormat class to do the needful for you
String date = "Your input date"
DateFormat originalFormat = new SimpleDateFormat("<Your Input format here>", Locale.US)
DateFormat targetFormat = new SimpleDateFormat("<Your desired format here>", Locale.US)
Date Fdate = originalFormat.parse(date)
formattedDate = targetFormat.format(Fdate)
public static String formatDate(String fromFormat, String toFormat, String dateToFormat) {
SimpleDateFormat inFormat = new SimpleDateFormat(fromFormat);
Date date = null;
try {
date = inFormat.parse(dateToFormat);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat outFormat = new SimpleDateFormat(toFormat);
return outFormat.format(date);
}
Use:
formatDate("dd-MM-yyyy", "EEEE, dd MMMM yyyy","26-07-2019");
Result:
Friday, 26 July 2019
i have a string "12/3/2014 12:00:00 AM" and i want to cast this string in date which have format like this "yyyy-MM-dd HH:mm:ss"
#DatabaseField(columnName="out_date",dataType=DataType.DATE_STRING,format="yyyy-MM-dd HH:mm:ss")
private Date out_date;
above is the object to get value from date string
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
outlet.setOut_date(formater.parse(json.getString("outletDate")));
after i using like the error occur java.text.ParseException: Unparseable date: ... (at offset 2) how to solve that problem thank in advance
Based on this answer, you need something like this. First convert your string in its present format to a date object, then reformat the date object.
String date = "12/3/2014 12:00:00 AM";
SimpleDateFormat sdf = new SimpleDateFormat("mm/dd/yyyy HH:MM:SS a");
Date testDate = null;
try {
testDate = sdf.parse(date);
}catch(Exception ex){
ex.printStackTrace();
}
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String newFormat = formatter.format(testDate);
System.out.println(".....Date..."+newFormat);
Conversion steps :
Create date object from your date format.
Target date format provide to SimpleDateFormat class constructor.
Parse date using SimpleDateFormat.
The code provided convert yyyy-MM-dd HH:mm:ss to dd/mm/yyyy HH:mm:ss format.
try {
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/mm/yyyy HH:MM:SS a");
Date date = sdf1.parse("12/3/2014 12:00:00 AM");
String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
System.out.println(format);
}catch(Exception e){
e.printStackTrace();
}
Error : java.text.ParseException: Unparseable date: ... (at offset 2) indicates that you are using wrong date format to parse your sting.
I'm currently working on some simple project in Java and I have date in the following string:
String dateString = "Sun 7/14 03:44 AM 2013";
and want to to convert this string to Date object. I'm using following lines of code to do that. I searched site and found solution how to do this with DateFormatter:
DateFormat format = new SimpleDateFormat("EEE M/dd hh:mm a yyyy");
Date d = format.parse(dateString);
But I'm probably doing something wrong, because I always get exception:
Unparseable date: "Sun 7/14 03:44 AM 2013"
This seems to be problem with pattern I'm using but tried different patterns and nothing work.
Certain fields such as the day of week fields and/or AM/PM marker may not match those from your default Locale. ParseException has the method getErrorOffset to determine exactly where the pattern does not match.
try
DateFormat format =
new SimpleDateFormat("EEE M/dd hh:mm a yyyy", Locale.ENGLISH);
It is important to add Locale as you are parsing language day of week names.
String dateString = "Sun 7/14 03:44 AM 2013";
DateFormat format = new SimpleDateFormat("EEE M/dd hh:mm a yyyy", Locale.US);
Date d = format.parse(dateString);
I tried this out and the following worked,
String stringDate = "Sun 7/14 03:44 AM 2013";
DateFormat format = new SimpleDateFormat("EEE MM/dd hh:mm a yyyy");
System.out.println("Parsed Date = "+format.parse(stringDate));
The output was as follows
Parsed Date = Sun Jul 14 03:44:00 BST 2013
SimpleDateFormat formatter = new SimpleDateFormat("/* type your own format*/");
String formattedDate = formatter.format(todaysDate);
System.out.println("Formatted date is ==>"+formattedDate);
try this code
The modern answer for the sake of completeness. While the other answers were good answers in 2013, Date, DateFormat and SimpleDateFormat are now long outdated, and I recommend you replace them with their modern counterparts:
DateTimeFormatter parser
= DateTimeFormatter.ofPattern("EEE M/dd hh:mm a yyyy", Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(dateString, parser);
The result is a LocalDateTime of 2013-07-14T03:44 as expected.
The format pattern string is still the same, and the need for an English language locale is the same.
In my application I need to compare two different dates given in below formats.
Inputs:
there are 2 input dates in String format.
String actual="11/12/2012 11:26:04 AM";
String expected="21/12/2012 09:49:12 AM";
I am trying to use below java code for comparision.
SimpleDateFormat format= new SimpleDateFormat("dd/MM/YYYY hh:mm:ss a");
Date date1 = format.parse(actual);
System.out.println("Formated date1 is: "+format.format(date1).toString());
// prints : 01/01/2012 11:26:04 AM Why????
Date date2= format.parse(expected);
System.out.println("Formated date2 is: "+format.format(date2).toString());
// prints : 01/01/2012 09:49:12 AM Why????
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
if( !(cal1.compareTo(cal2)<=0))
{
result=false;
String errMsg +="Actual:"+actual+" date is not before or equal to expected:"+expected+" date\n";
System.out.println(errMsg);
}
But the above code is not working as expected. please check the wrong output mentioned in comments
I think there is something wrong with the formatting.
can anyone please help me.
your format should be :
SimpleDateFormat format= new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
Notice year in lowercase y
Try:
SimpleDateFormat format= new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
The Ys should be lowercase.
You can use Joda Time. It has really nice methods, like isBefore()
String actual = "11/12/2012 11:26:04 AM";
String expected = "21/12/2012 09:49:12 AM";
DateTimeFormatter fmt = DateTimeFormat.forPattern("dd/MM/YYYY hh:mm:ss a");
DateTime dateTime1 = fmt.parseDateTime(actual);
DateTime dateTime2 = fmt.parseDateTime(expected);
if (dateTime1.isBefore(dateTime2)) {
System.out.println("awesome");
}