Date conversion in java? - java

I have this date:2/23/2016 4:28:46 PM
String d="2/23/2016 4:28:46 PM";
Format formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
try {
Date date = ((DateFormat) formatter).parse(d);
formatter = new SimpleDateFormat("dd MMM HH:mm a");
String notDate = formatter.format(date);
holder.tvNotificationTime.setText(notDate);
System.out.println(notDate);
} catch (ParseException e) {
e.printStackTrace();
}
I want the output as
23 Feb 4:28 PM
But I get output as
23 Feb 04:28 am
What's wrong here?

Use one H in the second DateFormat object:
formatter = new SimpleDateFormat("dd MMM h:mm a");
You also need to the AM/PM marker for the first formatter:
Format formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
See this note from the Javadocs:
Number: For formatting, the number of pattern letters is the minimum number of digits, and shorter numbers are zero-padded to this amount. For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields.

How about this:
Date date1 = new Date("2/23/2016 4:28:46 PM");
SimpleDateFormat sdf = new SimpleDateFormat("dd MMM hh:mm:ss a");
String formattedDate = sdf.format(date1);
System.out.println("Formatted Date: "+formattedDate);

Related

How to convert Date to a particular format in android?

"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

Difference between hh:mm a and HH:mm a

Here is my original code-
String dateString = "23 Dec 2015 1:4 PM";
Locale locale = new Locale("en_US");
SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm a");
DateFormat df = new SimpleDateFormat("dd MMM yyyy HH:mm a", locale);
Date date = null;
try {
date = formatter.parse(dateString);
} catch (ParseException e) {
LOGGER.error(e);
}
String newDate = df.format(date);
System.out.println("oldDate = " + dateString);
System.out.println("newDate = " + newDate);
and here is my output-
oldDate = 23 Dec 2015 1:4 PM
newDate = 23 Dec 2015 01:04 AM
There is AM-PM difference between the oldDate and newDate. Now I changed the DateFormat code to-
SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy hh:mm a");
DateFormat df = new SimpleDateFormat("dd MMM yyyy hh:mm a", locale);
and I get the expected output, which is-
oldDate = 23 Dec 2015 1:4 PM
newDate = 23 Dec 2015 01:04 PM
I'm aware that HH signifies the 24 hour format and hh signifies the 12-hour format.
My question is
If I use HH:mm a instead of hh:mm a, shouldn't this be returning the time in 24-hour format?
(or)
If it defaults to 12-hour format, shouldn't it return respective AM/PM marker depending on the date input provided?
This is just for my understanding.
Updated Answer
Here the problem is with Program flow
SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm a");
this simple date formatter is used to format the date string the Date object is created, here is the important part of answer
As you are using HH instead of hh, the SimpleDateFormater considers that provided date string is in 24-Hour Format and simply ignores the AM/PM marker here.
The Date Object from constructed from this SimpleDateFormatter is passed to the
DateFormat df = new SimpleDateFormat("dd MMM yyyy HH:mm a", locale);
That's why it's printing
newDate = 23 Dec 2015 01:04 AM
if you change the line
SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm a");
with
SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy hh:mm a");
Everything will go smooth as it should!
Note : when creating a locale you should pass the language code to the Locale() constructor. en-us not en_us.
IMP : Code is tested on Java 8 also. Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Difference between hh:mm and HH:mm:
HH:mm => will look like 00:12, 23:00... this has 24 hour format.
hh:mm => will look like 01:00Am, 02:00Am,...01:00pm this has 12 hour format.
And the a in hh:mm a or in HH:mm a is Am/pm marker for more info go to link
A simple test is the best answer to how the pattern "HH:mm a" is interpreted. First let us investigate the printing mode:
The old format engine SimpleDateFormat:
Calendar cal = new GregorianCalendar(2015, 3, 1, 17, 45);
SimpleDateFormat sf = new SimpleDateFormat("HH:mm a", Locale.US);
System.out.println(sf.format(cal.getTime())); // 17:45 PM
Java-8 (with the new package java.time.format):
LocalTime time = LocalTime.of(17, 59);
DateTimeFormatter tf = DateTimeFormatter.ofPattern("HH:mm a", Locale.US);
System.out.println(tf.format(time)); // 17:59 PM
Here we don't observe any override in both cases. I prefer that approach because using the combination of "HH" and "a" is in my opinion rather an indication for a programming error (the user has obviously not thought enough about the meaning and official description of those pattern symbols).
Now let us investigate the parsing mode (and we will use strict mode to observe what is really going behind the scene):
String dateString = "23 Dec 2015 1:4 PM";
SimpleDateFormat df = new SimpleDateFormat("dd MMM yyyy H:m a", Locale.US);
df.setLenient(false);
Date date = df.parse(dateString);
// java.text.ParseException: Unparseable date: "23 Dec 2015 1:4 PM"
How is the behaviour in Java-8? It is the same but with a clearer error message:
DateTimeFormatter tf = DateTimeFormatter.ofPattern("H:m a", Locale.US);
tf = tf.withResolverStyle(ResolverStyle.STRICT);
LocalTime.parse("1:4 PM", tf);
// DateTimeException: Cross check failed: AmPmOfDay 0 vs AmPmOfDay 1
This message tells us that the parsed hour (in 24-hour format!) with value "1" indicates AM while the text input contains the other parsed AM/PM-value "PM". This ambivalence cannot be resolved.
Lesson: We have to be careful with lenient parsing where contradictious information can be ignored and lead to false assumptions. The accepted answer of #Arjun is completely wrong.
By the way: Please use Locale.US or new Locale("en", "US") instead of new Locale("en-US") because the language "en-US" does not exist.

Prevent invalid date from getting converted into date of next month in jdk6?

Consider the snippet:
String dateStr = "Mon Jan 32 00:00:00 IST 2015"; // 32 Jan 2015
DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
DateFormat ddMMyyyy = new SimpleDateFormat("dd.MM.yyyy");
System.out.println(ddMMyyyy.format(formatter.parse(dateStr)));
gives me the output as
01.02.2015 // Ist February 2015
I wish to prevent this to make the user aware on the UI that is an invalid date?
Any suggestions?
The option setLenient() of your SimpleDateFormat is what you are looking for.
After you set isLenient to false, it will only accept correctly formatted dates anymore, and throw a ParseException in other cases.
String dateStr = "Mon Jan 32 00:00:00 IST 2015"; // 32 Jan 2015
DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
formatter.setLenient(false);
DateFormat ddMMyyyy = new SimpleDateFormat("dd.MM.yyyy");
try {
System.out.println(ddMMyyyy.format(formatter.parse(dateStr)));
} catch (ParseException e) {
// Your date is invalid
}
You can use DateFormat.setLenient(boolean) to (from the Javadoc) with strict parsing, inputs must match this object's format.
DateFormat ddMMyyyy = new SimpleDateFormat("dd.MM.yyyy");
ddMMyyyy.setLenient(false);
Set the date formatter not to be lenient...
DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
formatter.setLenient(false);

How to parse 'dd MMM yyyy'

How to convert date fromat from "dd MMM yyyy" to "yyyy-MM-dd"?
I know I have to use SimpleDatFormat but it doesn't work, neither does any solution from similar questions.
I have a date "18 Dec 2015" that I am trying to format but I get this
java.text.ParseException: Unparseable date: "18 Dec 2015"
Here's my code:
public String parseDate(String d) {
String result = null;
Date dateObject = null;
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd MMM yyyy");
try {
dateObject = dateFormatter.parse(d);
dateFormatter.applyPattern("yyyy-MM-dd");
result = dateFormatter.format(dateObject);
} catch (ParseException e) {
System.out.println(e);
}
return result;
}
Did you try
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MMM-yyyy");
instead of
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd MMM yyyy");
(note the hyphens, since your pattern doesn't match your input)
Also helpful: using Locale.US as recommended by #ZouZou
You are passing input as "18-Dec-2015" instead of the form "dd MMM yyyy". Try and pass input like 18 Dec 2015 and it should work.

Parse Exception in SimpleDateFormat

I am using SimpleDateFormat and I am getting ParseException as shown below.
java.text.ParseException: Unparseable date: "Mon Jul 02 21:56:10 AST 2012"
Code I have have is
String dateStr = "Mon Jul 02 21:56:10 AST 2012";
DateFormat readFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy ");
DateFormat writeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = readFormat.parse(dateStr);
} catch (ParseException e) {
System.out.println("Error in parsing date ********");
}
String formattedDate = "";
if (date != null) {
formattedDate = writeFormat.format(date);
}
System.out.println("Formatted date is " + formattedDate);
Any idea where I am going wrong?
Update 1
I also tried with
DateFormat readFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy ");
^
but still same exception.
Your code works (with z, and not Z), as soon as I specify that the date format should use the symbols of the English locale:
SimpleDateFormat readFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
readFormat.setDateFormatSymbols(DateFormatSymbols.getInstance(Locale.ENGLISH));
As per eran, you also have extra space after yyyy: yyyy "). Remove that extra space.
The format code Z is for timezone offset, like -0800, while the format code z is for the written format, such as PST or CST, according to what's described at SimpleDateFormat. Double-check that your parse pattern has the intended capitalization.

Categories

Resources