SimpleDateFormat, need textual Month - java

I have this as a string 02/06/2012 1:25 PM EST
I want to use SimpleDateFormat to return "Feb" from that data
Here is what I tried
SimpleDateFormat gottenDate = new SimpleDateFormat("MMM");
String month = "";
try {
month = gottenDate.format(gottenDate.parse("02/06/2012 1:25 PM EST"));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Unfortunately gottenDate.parse("02/06/2012 1:25 PM EST") gets a parse exception when the SimpleDateFormat documents say it should work.
If I do SimpleDateFormat gottenDate = new SimpleDateFormat("MM"); with two M's instead of 3, it returns "02" for me, as expected. The documents say that 3 or more M's should return a textual month. This doesn't happen, why? And yes, by now I could have made a string array of months and matched them to the numberic month SDF returned for me, but I am curious.
How do I make it work for me, thank you!

Exception is expected in your case:
SimpleDateFormat gottenDate = new SimpleDateFormat("MMM");
gottenDate.parse("02/06/2012 1:25 PM EST");
"gottenDate" is set up to parse a string if it matches "MMM" pattern. The following should work:
SimpleDateFormat gottenDate = new SimpleDateFormat("MMM");
gottenDate.parse("Feb");
Hopefully you can see what's going on here.

You need a format to parse the date: MM/dd/yyyy, and once you have a Date object from this first date format, you need a second one: MMM, to format the date as you want.
Formatting with MM will give you the month on two digits, and parsing with MMM will expect an abbreviated textual month, and won't parse 02.

You need two separate SimpeDateFormat instances with corresponding format strings to parse source date and format it back into short month form. Your format instance can't parse full date because it expecting only month in specified string.
SimpleDateFormat monthDate = new SimpleDateFormat("MMM");
SimpleDateFormat gottenDate = new SimpleDateFormat("dd/MM/yyyy h:mm a z");
String month = "";
try {
month = monthDate .format(gottenDate.parse("02/06/2012 1:25 PM EST"));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Not sure about format of your source string, complex format strings are little tricky.

This is the code that will get MonthName to you:
public String getMonthName(String dtstr, String fmt) throws ParseException {
SimpleDateFormat gottenDate = new SimpleDateFormat(fmt);
SimpleDateFormat month = new SimpleDateFormat("MMM");
Date dt = gottenDate.parse(dtstr);
return month.format(dt);
}
Call it like this:
System.out.println(getMonthName("01/06/2012 1:25 PM EST"), "M/d/y");
OUTPUT:
Feb

Well, others were faster answering, but I think this will do what you want.
String date_str = "02/06/2012 1:25 PM EST";
SimpleDateFormat in_format = new SimpleDateFormat("MM/dd/yyyy h:mm aa zzz");
SimpleDateFormat out_format = new SimpleDateFormat("MMM");
Date my_date = in_format.parse(date_str);
String out_str = out_format.format(my_date);
System.out.println(out_str); // Prints Feb
Dates and times can get complicated because of the way people in different record times. The best reference I've found for understanding all this is here:
http://www.odi.ch/prog/design/datetime.php

Just to provide an alternative solution, since your jobs is to "extract" the month of a Date, I think Calendar best fits the job.
// Construct a Date object
final DateFormat df = new SimpleDateFormat("M/d/y");
final Date originalDate = df.parse("02/06/2012 1:25 PM EST");
final Calendar c = Calendar.getInstance();
c.setTime(originalDate); // set the calendar Date
// Extract the month
String month = c.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.US);
System.out.println(month);

Related

Unparseable date with SimpleDateFormatter

I have a date that keeps giving me an error of
java.text.ParseException: Unparseable date: " 5 April 2017  "
All other dates (without word months) work fine
The code I am using is below:
VisitDate=VisitDate.trim();
if (VisitDate.matches(".*[a-z].*")){
SimpleDateFormat changeDate = new SimpleDateFormat("dd_MMM_yy", Locale.UK);
//Convert the string to a date
Date date = changeDate.parse(VisitDate);
//Reformat the date the way I like it
SimpleDateFormat dt1 = new SimpleDateFormat("dd_MM_yy");
//Convert back into a string
try {
VisitDate=dt1.format(date);
if(VisitDate==null){
SimpleDateFormat dt2 = new SimpleDateFormat("dd MM yy");
//Convert back into a string
VisitDate=dt2.format(date);
if(VisitDate==null){
SimpleDateFormat dt3 = new SimpleDateFormat("dd MMMM yy");
//Convert back into a string
VisitDate=dt3.format(date);
if(VisitDate==null){
SimpleDateFormat dt4 = new SimpleDateFormat("d_MMM_yy");
//Convert back into a string
VisitDate=dt4.format(date);
if(VisitDate==null){
SimpleDateFormat dt5 = new SimpleDateFormat("d_MMMM_yy");
//Convert back into a string
VisitDate=dt5.format(date);
if(VisitDate==null){
SimpleDateFormat dt6 = new SimpleDateFormat("dd_MMM_yy");
//Convert back into a string
VisitDate=dt6.format(date);
if(VisitDate==null){
SimpleDateFormat dt7 = new SimpleDateFormat("dd_MMM_yyyy");
//Convert back into a string
VisitDate=dt7.format(date);
if(VisitDate==null){
SimpleDateFormat dt8 = new SimpleDateFormat("dd_MMMM_yyyy");
//Convert back into a string
VisitDate=dt8.format(date);
if(VisitDate==null){
VisitDate=VisitDate.replaceAll("\\s", "");
SimpleDateFormat dt9 = new SimpleDateFormat("dd MMMM yyyy");
//Convert back into a string
VisitDate=dt9.format(date);
}
}
}
}
}
}
}
}
} catch (Exception e) {
Logger.error(e+"->No visit Date frmo here with the original date as: "+date);
}
}
Happy to read your expressed interest in the modern date and time classes, here’s just a snippet to get you started:
String visitDate = " 5 April 2017 ";
DateTimeFormatter parseFormatter
= DateTimeFormatter.ofPattern("d MMMM uuuu", Locale.UK);
visitDate = visitDate.trim();
LocalDate date = LocalDate.parse(visitDate, parseFormatter);
// reformat to the string we like
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd_MM_uu");
visitDate = date.format(formatter);
The result is
05_04_17
I have spelled visitDate with a small v since the Java coding conventions recommend that variable names begin with a small letter.
The uu is subtle and probably something you can ignore. It’s a signed year where 0 equals 1 BC, -1 equals 2 BC and so forth. Assuming none of your dates are that old, you can use u and y interchangeably.
I believe that neither SimpleDateFormat.format() nor LocalDate.format() will ever return null, so all your null checks are superfluous.
Link for further reading: Oracle tutorial: Trail: Date Time
You only have one SimpleDateFormatter being used for parsing:
SimpleDateFormat changeDate = new SimpleDateFormat("dd_MMM_yy", Locale.UK);
//Convert the string to a date
Date date = changeDate.parse(VisitDate);
It is using the format dd_MMM_yy, however you are passing 4 digits for the year.
The rest of your SimpleDateFormatters are being used for formatting to a string, not parsing from a string. Only the first one will be called, since it will be able to produce a string given a valid date, and the following null checks will stop any other formatters from being used.
You have the input string to parse like this: " 5 April 2017 ". But you have no pattern match for this input
First please trim the space of input string
Second please change the format of your string or add another pattern to parse this string, because you have month April with 5 letter, but you have no pattern with MMMMM. Usually the month will be shorten to 3 letter like: April -> Apr, March -> Mar ...

Create a function that takes string object and returns Date object in dd-MM-yyyy format [duplicate]

This question already has answers here:
display Java.util.Date in a specific format
(11 answers)
Closed 6 years ago.
I have date in string object. I want to convert into Date object.
Date getDateFmString(String dateString)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date convertedCurrentDate = sdf.parse(dateString);
return convertedCurrentDate ;
}
above function returning following output.
Fri Apr 22 00:00:00 IST 2016
but I want output in this format '2016-03-01' only
function should take string only.
function should return Date object.
I have done lot of research over web, but I got solution from one Expert.
Date getDateFrmString(String dDate)
{
java.sql.Date dDate = new java.sql.Date(new SimpleDateFormat("yyyy-MM-dd").parse(sDate).getTime());
return dDate;
}
this is what I want.
Change the date format from
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
to
SimpleDateFormat sdf = new SimpleDateFormat("dd-mm-yyyy");
Hope this works
See this example
public Class DateFormatDemo{
public static void main (String args[]) {
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy);
String dateInString = "01/01/2015";
try{
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
}catch(ParseException e){
e.printStackTrace();
}
}
}
This link might help you with string to date object conversions
You are parsing with the wrong format try
String dateString="01-01-2016";
SimpleDateFormat sdfP = new SimpleDateFormat("dd-MM-yyyy");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date convertedCurrentDate = sdfP .parse(dateString);
String date=sdf.format(convertedCurrentDate );
System.out.println(date);
Output:
2016-01-01
DEMO1
And if you want the format to dd-MM-yyyy then no need to define seperate SimpleDateFormat object.
String dateString="01-01-2016";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date convertedCurrentDate = sdf.parse(dateString);
String date=sdf.format(convertedCurrentDate );
System.out.println(date);
OUTPUT:
01-01-2016
DEMO2
To format the string date you have to first parse the String to Date object using the same format of date which the String have then format it using the desired format as seen in the above code.
Date objects don't have a format. Only a String does. A Date object will be output with whatever format you tell it to be format as. It all depends on what the format of the DateFormat object is when you call .format(). Calling the toString() method on a Date object uses a DateFormat of "dow mon dd hh:mm:ss zzz yyyy".
Let's do it step by step:
You have a date as String in dd-MM-yyyy format.
You want to convert it into date. (for this you are using SimpleDateFormat)
Now you are printing the date. Question here is are you printing the converted date object or input string?
If its a date object then toString method is called of date class.
As per comment on java.util.Date class it's:
dow mon dd hh:mm:ss zzz yyyy
similar to
Fri Apr 22 00:00:00 IST 2016
So that coincides with what you get in output in the second approach. But how is that code even running is strange.
String inputStr = "11-11-2012";
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date inputDate = dateFormat.parse(input);
Variable 'input' is not defined.
What are the possible solutions:
While printing date, convert it back to String using SimpleDateFormat as per the requirement.
Date d =new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dStr = sdf.format(dateString);
System.out.printn(dStr);
Extending class java.util.Date and override toString, but that would be a bad idea.

How can i get data in format "YYYY-MM-DD 00:00:00.0" using class Date?

How can i get data in format "YYYY-MM-DD 00:00:00.0" using class Date (it's extremly important to use exactly this class)?
I tried to do everything i can think of:
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
df.format(date)
and
String pattern = "yyyy-MM-dd HH:mm:ss.S";
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
Date date = format.parse("2011-01-18 00:00:00.0");
} catch (ParseException e) {
e.printStackTrace();
}
byt when i print date using logger i get this format "Tue Sep 30 00:00:00 MSK 1913".
Try this
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
Date date = format.parse("2011-01-18 00:00:00.0");
System.out.println(format.format(date));
Are you sure you want the hours, minutes, secs to be zeroes?
Or do you mean the pattern yyyy-MM-dd HH:mm:ss ?
The date class is always independent of the formatting. It only needs to be translated when you print it, like this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String out = df.format(date)
System.out.println(out);
Or do you want to strip the time out of the date object? or something.
You are confused by Date.toString() and SimpleDateFormat.format()
An object of Date (java.util.Date) has no format information. If you call date.toString(), (which is called by your logger), you got default representation of this object, you have seen what it is.
However, SimpleDateFormat.format() will give you a string as return value, this value will format the Date object with a pattern defined by SimpleDateFormat.
In your code, you first parsed the string, with certain pattern, to get the date object. If it was successful, you got the Date object, here, for this date object, you don't have any format information, even if you have defined a pattern to parse the input string. If you want to print/output (to string again) the date object, you have to use the SimpleDateFormat.format() method.
I hope the below one will solve your problem when you need to do for dynamic dates.
Date today = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
String formattedDate = sdf.format(today);
System.out.println(formattedDate);
//Above line output (formatted String object) is 2017-12-29 00:00:00
System.out.println(format.format(formattedDate));
//Above line output(parsed Date object) is Fri Dec 29 00:00:00 IST 2017
For Date object you can't get the output as yyyy-MM-dd 00:00:00, but you will get this format in String object type.

Exception in parsing date format [duplicate]

This question already has answers here:
Date Format JAVA
(5 answers)
Closed 9 years ago.
I have a date in the following format
//input date
Thu Jun 06 2013 00:00:00 GMT+0530 (India Standard Time)
//output date format
I want to change this to "dd-mm-yyyy, hh:mm:ss".
I get the input date format from db. I have to change that into output date format which i will be showing it in a grid.
I tried the following code.
DateFormat outputDate = new SimpleDateFormat("dd-mm-yyyy, hh:mm:ss");
try
{
Date date = outputDate.parse(facade.getDate.toString()); **//getting exception here**
outputDate = new SimpleDateFormat("dd-mm-yyyy, hh:mm:ss");
Date date1 = new SimpleDateFormat("dd-mm-yyyy, hh:mm:ss").parse(outputDate
.format(date));
facade.setDate(date1);
}catch (ParseException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
I am getting
java.text.ParseException: Unparseable date: "2013-06-06 00:00:00.0".
Any help..
"2013-06-06 00:00:00.0" does not match "dd-mm-yyyy, hh:mm:ss" your format should be "dd-MM-yyyy hh:mm:ss" instead
But, looking at your code I'm guessing facade.getDate is actually a java.sql.Timestamp which inherits from java.util.Date so you can directly pass it to the format like so
new SimpleDateFormat("dd-MM-yyyy, hh:mm:ss").format(facade.getDate)
Here's some code which works for me:
import java.text.*;
import java.util.*;
public class Test {
public static void main(String[] args) throws Exception {
String input = "Thu Jun 06 2013 00:00:00 GMT+0530 (India Standard Time)";
DateFormat inputFormat = new SimpleDateFormat("E MMM dd yyyy HH:mm:ss 'GMT'z",
Locale.ENGLISH);
Date date = inputFormat.parse(input);
DateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss",
Locale.ENGLISH);
outputFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String output = outputFormat.format(date);
System.out.println(output);
}
}
Things to consider:
You need to work out your output time zone. Currently I've got it set to UTC, but that may not be what you want.
You really need to take a step back and think things through. You've clearly got two different formats - you're trying to convert from one to the other. So creating three different SimpleDateFormat objects all with the same format is never going to work.
You need to read documentation carefully... in SimpleDateFormat, M means month and m means minute; h uses the 12-hour clock and H uses the 24-hour clock.
This is assuming you actually need to start with a string though. If getDate is already a Date or a Timestamp, you can ignore the first part - just use the output part of the above code. You should avoid unnecessary string conversions wherever possible.
Note that dd-MM-yyyy is a slightly unusual format - are you sure you don't actually want yyyy-MM-dd which is more common (and sortable)?
DateFormat outputDate = new SimpleDateFormat("yyyy-dd-mm hh:mm:ss");
try {
Date date = outputDate.parse("2013-06-06 00:00:00.0");
System.out.println(new SimpleDateFormat("dd-mm-yyyy, hh:mm:ss").format(date));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
works well, line 1 was incorrect. Your SimpleDateFormat.parse needs to be in the exact format of the input date. Then you want to output it in a different format so you make another one and set the format then call SimpleDateFormat.format(date) and I put a println on it.
Fault is here
DateFormat outputDate = new SimpleDateFormat("dd-mm-yyyy, hh:mm:ss");
pattern should be equals to Thu Jun 06 2013 00:00:00 GMT+0530 (India Standard Time). not to your out put strings pattern.
#Test
public void test() throws ParseException {
SimpleDateFormat sdf_org = new SimpleDateFormat("E MMM dd yyyy HH:mm:ss 'GMT'Z", Locale.ENGLISH);
Date d = sdf_org.parse("Thu Jun 06 2013 00:00:00 GMT+0530");
SimpleDateFormat sdf_target = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss.SSS");
System.out.println(sdf_target.format(d));
}
output console : 2013-30-06 03:30:00.000

Java ParseException while attempting String to Date parsing

I'm having a hard time Parsing/Formatting a Date string received back from a web service. I've attempted multiple approaches, but with no luck.
Sample Date String:
2011-10-05T03:00:00Z
Exception:
W/System.err(10072): java.text.ParseException: Unparseable date: "2011-10-05T05:00:00Z" (at offset 10)
W/System.err(10072): at java.text.DateFormat.parse(DateFormat.java:626)
Sample Code:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:SSSS");
Date date = formatter.parse(info.AiringTime);
I've found that if I remove the "T" between the date and the time and replace it with a space, it will format just fine. Anybody have any suggestions?
--UPDATE--
After looking deeper into the API documentation, I found this:
All response DateTime values are in UTC format. You need to apply the UTC offset to calculate the local time for display.
DateTime is a date-and-time value specified in one of the following formats:
UTC format: YYYY-MM-DDThh:mm:ssZ. For example: 2011-03-15T02:00:00Z.
Local time with an offset: YYYY-MM-DDThh:mm:ss + or - hh:mm (positive or negative offset). For example, for US Pacific time: 2011-03-14T06:00:00 -08:00.
Any suggestions on the UTC format approach?
You could try:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String dateString = dateString.replace("Z", "GMT+00:00");
Date date = dateFormat.parse(dateString);
The above code should correctly handle the case where a timezone is specified in the date. As Z represents the UTC/GMT timezone it is replaced by GMT so the SimpleDateFormat can interpret it correctly (i would love to know a cleaner way of handling this bit if anyone knows one).
Try,
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
This pattern should parse the date you provide: "yyyy-MM-dd'T'HH:mm:ss'Z'".
If you want to use SimpleDateFormat and you have a limited number of variations, you can create separate formatters for each pattern and chain them:
Date date = formatter1.parse(info.AiringTime);
if (date == null)
{
date = formatter2.parse(info.AiringTime);
if (date == null)
{
date = formatter2.parse(info.AiringTime);
if (date == null)
{
date = formatter3.parse(info.AiringTime);
}
}
}
or put them in a list and iterate until non-null or no more formatters.
If you have too many patterns for this to be practical, you can parse it yourself or try one of these libraries.
This worked for me
SimpleDateFormat isoDateFormat = new SimpleDateFormat("yyyy-mm-dd'T'hh:mm:ss'Z'");
SimpleDateFormat viewFriendlyDateFormat = new SimpleDateFormat("dd/MMM/yyyy hh:mm:ss aaa");
String viewFriendlyDate = "";
try {
Date date = isoDateFormat.parse(timestamp);
viewFriendlyDate = viewFriendlyDateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat isoDateFormat = new SimpleDateFormat("yyyy-mm-dd'T'hh:mm:ss'Z'");
SimpleDateFormat viewFriendlyDateFormat = new SimpleDateFormat("dd/MMM/yyyy hh:mm:ss aaa");
String viewFriendlyDate = "";
try {
Date date = isoDateFormat.parse(timestamp);
viewFriendlyDate = viewFriendlyDateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}

Categories