Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

format date from "MMM dd, yyyy HH:mm:ss a" to "MM.dd

Tags:

java

datetime

I want to format date from "MMM dd, yyyy HH:mm:ss a" to "MM.dd". I have following code

SimpleDateFormat ft = new SimpleDateFormat ("MMM dd, yyyy hh:mm:ss a");
t = ft.parse(date); //Date is Sep 16, 2015 10:34:23 AM and of type string.
ft.applyPattern("MM.dd"); 

but I am getting exception at t = ft.parse(date);

Please help

like image 541
Nishant Avatar asked Sep 16 '15 15:09

Nishant


People also ask

What date format has T and Z?

ISO 8601. This format is defined by the sensible practical standard, ISO 8601. The T separates the date portion from the time-of-day portion. The Z on the end means UTC (that is, an offset-from-UTC of zero hours-minutes-seconds).

What is DD format for date?

dd – two-digit day of the month, e.g. 02. ddd – three-letter abbreviation for day of the week, e.g. Fri. dddd – day of the week spelled out in full, e.g. Friday.


1 Answers

Three possible explanations:

  1. your default locale is incompatible with the input date - e.g. it can't understand Sep as a month name
  2. there's something wrong with the input string, or
  3. t is the wrong type (e.g. java.sql.Date instead of java.util.Date, or some other type altogether), or is not declared.

You should include details of the exception in your question to figure out which it is, but here's a working example using basically your own code, with the addition of a specific Locale.

SimpleDateFormat ft = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a", Locale.US);
java.util.Date t=ft.parse("Sep 16, 2015 10:34:23 AM");
ft.applyPattern("MM.dd");
System.out.println(ft.format(t));

output:

09.16
like image 179
CupawnTae Avatar answered Oct 13 '22 05:10

CupawnTae