How to convert Date to a particular format in android? - java

"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

Related

How do I change 'AM' to 'PM' in a Date Object JAVA [duplicate]

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

Date conversion in 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);

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.

Convert a date from 14 to 2014

How can I format a :
Tue May 21 00:00:00:00 GMT +200 14 <--- Tue May 21 00:00:00:00 GMT
+200 2014
i tried :
StringBuilder myName = new StringBuilder(datum);
myName.setCharAt(datum.length()-4, '2');
myName.setCharAt(datum.length()-3, '0');
Date date= null; DateTimeFormat.getFormat("-- idk ----").parse(myName.toString()); Window.alert(myName.toString());
but i dont know how to define the same date format as the Date class
i think this isnt a good solution is there a better?
I suppose that datum is a Date object.
So, just do:
DateFormat df = new SimpleDateFormat("EEE MMM d HH:mm:ss:SS z yyyy");
System.out.println(df.format(datum));
More info: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html.
// getFormatedDate("in which pattern you are sending date", "how we want", date in string form);
example : formatedDate = getFormatedDate("yyyy-MM-dd", "ddMMyyyy", "2014-05-21");
private String getFormatedDate(String baseFormat, String reqFormat, String dateStr) {
String formatedDate = null;
try {
DateFormat fromFormat = new SimpleDateFormat(baseFormat);
fromFormat.setLenient(false);
DateFormat toFormat = new SimpleDateFormat(reqFormat);
toFormat.setLenient(false);
java.util.Date date = fromFormat.parse(dateStr);
formatedDate = toFormat.format(date);
} catch (ParseException ex) {
}
return formatedDate;
}
You have to use date formatter.
Your date formatter should be
DateFormat dateFormat = new SimpleDateFormat("EEE MMM d HH:mm:ss:SS z yyyy");
Then use this formatter to get your desired date.
Just do:
newDate = dateFormat.format(yourOldDate);
Hope this will works.
Get more from:
http://www.mkyong.com/java/java-date-and-calendar-examples/
and http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
Thanks.

Date format issue in android

In android
am getting date in
(date = "04-01-2013") this format
but i want to show same date in
en.US format like (date="Friday,January 04,2013")
use SimpleDateFormat.
set input pattern matching input date string: "04-01-2013" -> "dd-MM-yyyy".
And output pattern like output: "Friday, January 04, 2013" -> "EEEE, MMMM dd, yyyy"
public String formatDate(String input){
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date d = sdf.parse(input);
sdf.applyPattern("EEEE, MMMM dd, yyyy");
return sdf.format(d,new StringBuffer(),0).toString();
}
try {
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
DateFormat df2 = new SimpleDateFormat("dd-MMM-yyyy");
return df2.format(df1.parse(input));
}
catch (ParseException e) {
return null;
}
You can use something like this
android.text.format.DateFormat.format("EEEE, MMMM dd, yyyy", new java.util.Date());
Take a look at DateFormat.
This is how you do it in java
SimpleDateFormat df=new SimpleDateFormat("EEEE,MMMM dd,yyyy");
java.util.Date date=df.parse("04-01-2013");
refer this

Categories

Resources