I have a string of day, date and time that is String myDateString = "Fri, 07 Jun 2013 09:30:00";.For date January 2, 2010 we use new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(mystring);. What can I use instead of MMMM d, yyyy in my situation
Now How can I extract day, year, month, day of the month, hours, minutes and seconds from the string in the following pattern.
day: Fri,
Year: 2013,
Month: Jun,
day of the Month: 07,
Hour: 09,
Minutes: 30 and
Seconds: 00,
Please help me in this respect I would be very thankful to you for this act of kindness. Thanks in advance.
Reference these formats Java Date Format Docs:
try this code:
Date tempDate = new SimpleDateFormat("E, dd MM yyyy HH:mm:ss").parse("Fri, 09 12 2013 09:30:00");
System.out.println("Current Date " +tempDate);
Use a SimpleDateFormat object to extract the date and put it into a util.Date object. From there extract the individual attributes you need.
try this:
String myDateString = "Fri, 07 Jun 2013 09:30:00";
Date myDate = null;
// attempting to parse the String with a known format
try {
myDate =
new SimpleDateFormat("E, dd MMM yy HH:mm:ss", Locale.ENGLISH)
.parse(myDateString);
}
// something went wrong...
catch (Throwable t) {
// just for debug
t.printStackTrace();
}
finally {
if (myDate != null) {
// just for checking...
System.out.println(myDate);
// TODO manipulate with calendar
}
}
This will work if you are certain that the format you receive will always be consistent.
You can then split your date into different values by initializing a Calendar object, then retrieving its various fields.
For instance:
// once you're sure the date has been parsed
Calendar calendar = Calendar.getInstance(myTimeZone, myLocale);
calendar.setTime(myDate);
// prints the year only
System.out.println(calendar.get(Calendar.YEAR));
You can use SimpleDateFormat from standard library. Something like following:
new SimpleDateFormat("E, dd MM yyyy HH:mm:ss").parse(myDateString);
The easiest solution is to split the string
String[] parts = "Fri, 07 Jun 2013 09:30:00".split("[ :,]+");
this will produce an array
[Fri, 07, Jun, 2013, 09, 30, 00]
then use its elements
String dayOfWeek = parts[0];
...
Related
The full date received from the request is of this format
Wed Mar 11 2020 05:29:01 GMT+0100 (West Africa Standard Time)
Now I substringed it to this - Wed Mar 11 2020
date.substring(0,15))
To enable me to save the date, I am parsing it as below
SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-dd", Locale.ENGLISH);
Date parsedDate = null;
try {
parsedDate = format.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
When the code is ran, I get below error
java.text.ParseException: Unparseable date: "Wed Mar 11 2020"
I have also tried parsing with
SimpleDateFormat format = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy",
Locale.ENGLISH);
based on SO answers and I am still getting date parsing error.
How can I parse this date - date.substring(0,15))
The format you need to match your date is EEE MMM dd yyyy e.g.
String date = "Wed Mar 11 2020 05:29:01 GMT+0100 (West Africa Standard Time)";
date = date.substring(0,15);
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd yyyy");
Date parsedDate = null;
try {
parsedDate = format.parse(date);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(parsedDate);
SimpleDateFormat outformat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(outformat.format(parsedDate));
Output:
Wed Mar 11 00:00:00 CET 2020
2020-03-11
Three points:
Do use java.time, the modern Java date and time API, for your date and time work.
Rather than taking a substring of the string you receive, I’d prefer to parse the entire string.
Your format pattern string must match the string you are trying to parse (and vice versa). Exactly.
In code:
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern(
"EEE MMM d uuuu HH:mm:ss 'GMT'xx (zzzz)", // Pattern to match your input strings.
Locale.UK // Locale determines human language used to parse name of month and such.
)
;
String dateString = "Wed Mar 11 2020 05:29:01 GMT+0100 (West Africa Standard Time)";
ZonedDateTime zonedDateTime = ZonedDateTime.parse(dateString, formatter);
Generate a string.
System.out.println( zonedDateTime.toString() );
Output from this snippet is:
2020-03-11T03:29:01+01:00[Africa/Lagos]
Use java.time. The modern API is sol much nicer to work with. The Date class that you used is poorly designed, and SimpleDateFormat notoriously troublesome. Don’t use any of those.
Parse the entire string. Taking a substring of length 15 will cause some readers of your code to wonder, some ask “WTF?”, some to use their precious time for counting to make sure that 15 is the correct length. Also taking a substring of length 15 is fragile unless you’re sure that the abbreviations for day of week and for month always have length three and day of month is always written with two digits (May 02, not May 2). Furthermore it’s easier to parse more than you need and throw information away later, than to parse just what you think you need and later discover that you needed one more bit.
Specifying the format. Since your string begins with a day of week abbreviation, you need a format pattern string that begins with the format pattern letter for day of week. In this case EEE (or E or EE) for the abbreviation (EEEE would have meant the day written in full, like Wednesday). So YYYY-MM-dd is all wrong. EE MMM dd HH:mm:ss z yyyy comes closer and can parse day of week, month and day of month. Then comes a space and a year in the input, but your format pattern string has yyyy for year at the end instead, so this is where parsing breaks for you. If writing the correct format pattern string teases (as it does for many), a trick is to try something and first use the formatter for formatting a date and time. If the result differs from the string we would like to parse, it usually gives us a hint about what’s wrong.
Link: Oracle tutorial: Date Time explaining how to use java.time.
Try this.
SimpleDateFormat sdf3 = new SimpleDateFormat("EEE MMM dd yyyy");
Date d1 = null;
try {
d1 = sdf3.parse("Wed Mar 30 2016");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(sdf3.format(d1));
}
Output:
Wed Mar 30 2016
First you need to control your computer language. According to your computer's language. You must write day's name and month's name in your computer's language
Actually you had better convert this 'Wed' according to your language.
My computer's language is turkish.
I used below code how to use day's name on date on java.
public static void main(String[] args) {
String sDate1 = "Per Mar-11-2020";
String sDate2 = "Perşembe Mar-11-2020";
Date date1;
try {
date1 = new SimpleDateFormat("EEE MMM-dd-yyyy").parse(sDate1);
System.out.println(sDate1+"\t\t"+date1);
date1 = new SimpleDateFormat("EEEEE MMM-dd-yyyy").parse(sDate2);
System.out.println(sDate2+"\t\t"+date1);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
output :
Per Mar-11-2020 Wed Mar 11 00:00:00 AST 2020
Perşembe Mar-11-2020 Wed Mar 11 00:00:00 AST 2020
Also you need to be carefull such as :
if your String is Per Mar-11-2020, you need to write EEE MMM-dd-yyyy.
Or
if your String is Per Mar 11 2020, you need to write EEE MMM dd yyyy.
Or
if your String is Per Mar/11/2020, you need to write EEE MMM/dd/yyyy.
I am getting the date in long format like this :
Wednesday, August 1, 2018
I want this in the below format:
Wed, Aug 01, 2018
I used the below code:
public static String getShortDate(Date date){
SimpleDateFormat format = new SimpleDateFormat("E, MMM dd, yyyy");
return format.format(date);
}
This works fine for en_US. But how to make it work for other locales
For example the long format for German is :
Samstag, 16. Juni 2018
how to get the above short format for it?
The getShortDate method parameter takes Date, but I can change it to String.
If the longer format is : Samstag, 16. Juni 2018
i need it to be : Sa., 16. Jun. 2018
i am using the below code :
SimpleDateFormat format = new SimpleDateFormat("E, dd MMM, yyyy", locale);
return format.format(date);
This is giving me output as: Sa, 16 Jun, 2018
How to get that dot(.) after Sa
To get short date format in different locale code, you could try below code:
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("E, MMM dd, yyyy", new Locale("de", "de"));//for german germany
String date = simpleDateFormat.format(new Date());
Output:
Di, Mär 27, 2018
I am trying to convert the date from May 15, 2009 19:24:11 PM MDT to 20090515192411.
But when I tried the below code, the readformat itself is taking the input as May 16 instead of May 15
Here is my code.
String dateInString = "May 15, 2009 19:24:11 PM MDT";
DateFormat readFormat = new SimpleDateFormat( "MMM dd, yyyy hh:mm:ss a z");
DateFormat writeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = null;
try {
date = readFormat.parse(dateInString);
}
catch(ParseException e) {
e.printStackTrace();
}
System.out.println(date); // Prints May 16, 2009 07:24:11 AM MDT
String formattedDate = "";
if( date != null ) {
formattedDate = writeFormat.format(date);
}
System.out.println(formattedDate); // Prints 20090516072411
Thanks for the help in advance.
String dateInString = "May 15, 2009 19:24:11 PM MDT";
is invalid, time could be either 24 hour format or it could have AM/PM
You need HH instead of hh to read a time in 24-hour format. Java's "lenient dates" are doing you in here - 19:24pm is being parsed as 8 hours after 11:24pm.
I need to change the input date format to my desired format.
String time = "Fri, 02 Nov 2012 11:58 pm CET";
SimpleDateFormat displayFormat =
new SimpleDateFormat("dd.MM.yyyy, HH:mm");
SimpleDateFormat parseFormat =
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm aa z");
Date date = parseFormat.parse(time);
System.out.println("output is " + displayFormat.format(date));
it gives me this error
java.text.ParseException: Unparseable date: "Fri, 02 Nov 2012 11:58 pm CET"
at java.text.DateFormat.parse(Unknown Source)
at Main.main(Main.java:10)
Can anyody help me? Because this code doesn't work.
It appears Android's z does not accept time zones in the format XXX (such as "CET"). (Pulling from the SimpleDateFormat documentation.)
Try this instead:
String time = "Fri, 02 Nov 2012 11:58 pm +0100"; // CET = +1hr = +0100
SimpleDateFormat parseFormat =
new SimpleDateFormat("EEE, dd MMM yyyy hh:mm aa Z"); // Capital Z
Date date = parseFormat.parse(time);
SimpleDateFormat displayFormat =
new SimpleDateFormat("dd.MM.yyyy, HH:mm");
System.out.println("output is " + displayFormat.format(date));
output is 02.11.2012, 22:58
Note: Also, I think you meant hh instead of HH, since you have PM.
Result is shown here. (This uses Java7's SimpleDateFormat, but Android should support RFC 822 timezones (+0100) as well.)
NB: Also, as it appears Android's z accepts full names ("Pacific Standard Time" is the example they give), you could simply specify "Centural European Time" instead of "CET".
Try out the following code:
SimpleDateFormat date_format = new SimpleDateFormat("yyyyMMMdd");
System.out.println(date_format.format(cal.getTime()));
It will work.. If not print the log cat? What erroe is coming?
First of All I must agree with #Eric answer.
You just need to remove "CET" from your string of date.
Here is sample code. Check it.
String time = "Fri, 02 Nov 2012 11:58 pm CET";
time = time.replaceAll("CET", "").trim();
SimpleDateFormat displayFormat =
new SimpleDateFormat("dd.MM.yyyy, HH:mm");
SimpleDateFormat parseFormat =
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm aa");
Date date = null;
try {
date = parseFormat.parse(time);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("output is " + displayFormat.format(date));
I am trying to convert a String DateTime value which is present in a flat file as a Date object after parsing the flat file in my code.
I have written the code to do that but when I format the date its always giving me a date more than 1 day for the specified value, some times it's adding 5:30.
Below is the code for that:
DateFormat f = new SimpleDateFormat("EEE MMM dd HH:mm:ss zz yyyy");
Date date = f.parse("Tue Aug 23 20:00:03 PDT 2011");
System.out.println("---date----" + date);
The output for the above is
---date----Wed Aug 24 08:30:03 IST 2011
Can you please let me know whats the issue here. Is there a problem in the pattern that I am using in the SimplaDateFormat class or is there a problem with the code.
I have been scratching my head on this for a long time now.
Can you please let me know whats the issue here.
Sure. You're effectively calling date.toString(), which doesn't know anything about the SimpleDateFormat which was used to parse the original text value. A Date is just an instant in time. It has no notion of a per-instance format. Additionally, it doesn't know about a time zone. You've given a value in PDT, which was then parsed... and when you print it, it's using the system local time zone (IST). That's what Date.toString always does.
If you want to format a Date in a particular way, using a particular format in a particular time zone, call DateFormat.format.
Your system timezone is different. The output is showing IST - or Indian Standard Time, which is an 12.5h difference from PDT. The code is properly parsing the given date which is PDT (UTC -7) and printing out IST (UTC +5h30).
Java stores Dates as UTC dates. So when you parse the PDT date, Java will convert it to UTC and store it internally as a UTC timestamp. When you print, if you do not specify the timezone, it will default to the system timezone, which in your case would appear to be IST.
To specify an exact timezone, specify it in the SimpleDateFormat:
DateFormat f = new SimpleDateFormat("EEE MMM dd HH:mm:ss zz yyyy");
f.setTimeZone(TimeZone.getTimeZone("PDT"));
Date date = f.parse("Tue Aug 23 20:00:03 PDT 2011");
System.out.println("---date----" + f.format(date));
Because you are not formatting a date. Look at the example
public static void main(String[] args){
Locale currentLocale = Locale.US;
DateFormat f = new SimpleDateFormat("EEE MMM dd HH:mm:ss zz yyyy", currentLocale);
Date date = null;
Date today;
try {
today = new Date();
String result = f.format(today);
System.out.println("Locale: " + currentLocale.toString());
System.out.println("Result: " + result);
date = f.parse("Tue Aug 23 20:00:03 PDT 2011");
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("---date----" + f.format(date));
}
will output
Locale: en_US
Result: Tue Sep 25 19:12:38 EEST 2012
---date----Tue Aug 23 20:00:03 PDT 2011
Now, you have a bit modified code
public static void main(String[] args){
Locale currentLocale = Locale.US;
DateFormat f = new SimpleDateFormat("EEE MMM dd HH:mm:ss zz yyyy", currentLocale);
DateFormat f2 = new SimpleDateFormat("EEE MMM dd HH:mm:ss zz yyyy", currentLocale);
Date date = null;
Date today;
try {
today = new Date();
String result = f.format(today);
System.out.println("Locale: " + currentLocale.toString());
System.out.println("Result: " + result);
date = f.parse("Tue Aug 23 20:00:03 PDT 2011");
System.out.println("---date----" + f.format(date));
System.out.println("---date----" + f2.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
}
which outputs to
Locale: en_US
Result: Tue Sep 25 20:42:10 EEST 2012
---date----Tue Aug 23 20:00:03 PDT 2011
---date----Wed Aug 24 06:00:03 EEST 2011
seems that SimpleDateFormat don't care about timezone even if 'z' pattern is specified. It is setting the timezone when it parses the input. That's how I can describe that a strange behavior. Then use of 'z' pattern seems obsolete and lead to unpredictable results.
so setting the TimeZone will fix the issue
f2.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));