Android: I can't figure out SimpleDateFormat - java

I have tried and tried, but I cannot get my RSS app to properly format the pubDate into a more user friendly format.
String str = "26/08/1994";
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); //please notice the capital M
Date date = formatter.parse(str);
That code looks simple enough, but I get an unhandled type parse exception error on formatter.parse(str). Once that gets working, I then need to convert my RSS Pubdate to MM/dd.
The line of code to set the text for that is here:
listPubdate.setText(myRssFeed.getList().get(position).getPubdate());
Do I just change that to:
listPubdate.setText(date);
This looks so simple that it's driving me nuts that I can't find the answer.

you can get the date by this
// get the current date
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
and want to put in simple format then
String date=String.format(mDay+"/"+mMonth+"/"+mYear);
so you can use this very easily.

It sounds to me like you are actually running this and getting the error. As others have pointed out, the problem is you need to wrap the formatter.parse call in a try/catch block. This is a compilation problem, not a runtime problem.
The code you have will work as you expect once you fix this compile problem.
Use a second formatter to get the MM/dd output you want.
String str = "26/08/1994";
SimpleDateFormat inputFormatter = new SimpleDateFormat("dd/MM/yyyy"); //please notice the capital M
SimpleDateFormat outputFormatter = new SimpleDateFormat("MM/dd");
try {
Date date = inputFormatter.parse(str);
String text = outputFormatter.format(date);
listPubdate.setText(text);
} catch (ParseException e ) {
e.printStackTrace();
}

I get an unhandled type parse exception error on formatter.parse(str)
For that, you'll need to explicitly handle the exception, either by declaring that the currently executing method just throws it, or by catching it. For more information, I highly recommend going through the Exceptions Lesson in the Java Tutorial.
Here's an example of catching the exception.
String str = "26/08/1994";
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); //please notice the capital M
Date date;
try
{
date = formatter.parse(str);
}
catch (ParseException e)
{
// Handle error condition.
}

SimpleDateformat.parse(String) throws a checked exception... wrap it in a try/catch block.

Below is the sample code ... pay attention to format inside SimpleDateFormat Constructor. This string which to be parsed for date should be similar in format to that of string passed in SimpleDateFormat constructor
public Date getDate(String str) {
SimpleDateFormat sdFormat = new SimpleDateFormat("EEE MMM dd hh:mm:ss");
Date d = null;
try {
String str1 = str.substring(0, str.lastIndexOf(" ")).substring(0,
str.lastIndexOf(" "));
String str2 = str1.substring(0, str1.lastIndexOf(" "));
Log.v("str1", str2);
d = sdFormat.parse(str2);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return d;
}

Related

How to convert date String from JSON to time span

The time value I get from JSON response is of format "sun dd/mm/yyyy - HH:mm" and I want to convert it to a time span instead (10 min ago, 2 days ago...). For that I made a method converts given String of dataTimeFormant into "X Hours Ago" format and returns x hours ago in a string format then I can put in a textView.
Everything seems correct, I think, but the app crashes on start with a NullPonterException to a line of my code, so probably I have made things wrong.
#RequiresApi(api = Build.VERSION_CODES.N)
public String dateConverter(String dateStringFormat) {
Date date = null;
SimpleDateFormat currentDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z");
try {
date = currentDateFormat.parse(dateStringFormat);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat requireDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDate = requireDateFormat.format(date);
long currentTimeInMilis = 0;
try {
Date currentDateObject = requireDateFormat.parse(currentDate);
currentTimeInMilis = currentDateObject.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
CharSequence timeSpanString = DateUtils.getRelativeTimeSpanString(currentTimeInMilis, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS);
return timeSpanString.toString();
}
My adapter onBindView method:
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int i) {
//...
//...
//...
DateConvert converter = new DateConvert();
String postTime = converter.dateConverter(this.news.get(i).getCreated());
viewHolder.articleCreatedDate.setText(postTime);
}
The logcat error points to:
String currentDate = requireDateFormat.format(date);
and :
String postTime = converter.dateConverter(this.post.get(i).getCreated());
I'm unable to find the cause because if I remove the call to that function everything works perfectly, probably there are better ways to achieve this?
Thanks.
I am new here, hopefully I can help.
The first thing I notice is there is no closing single quotation after 'Z:
SimpleDateFormat currentDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
Besides, the problem is the "currentDateFormat" does not portray the proper date input format which causes it not to be able to parse properly. If the input is "sun dd/MM/yyyy - HH:mm" then the format should be:
SimpleDateFormat currentDateFormat = new SimpleDateFormat("EEE MM/dd/yyyy '-' HH:mm");
Or
SimpleDateFormat currentDateFormat = new SimpleDateFormat("EEE MM/dd/yyyy - HH:mm");
Then date = currentDateFormat.parse(dateStringFormat); should be able to parse properly and the "date" will not have "null" value.
Hope this helps.

Setting an Input with separate year, month and day

I've set an AlertDialog.builder in which there is an input, to obtain a date from the user. Currently, it's set like that:
input.setInputType(InputType.TYPE_CLASS_DATETIME | InputType.TYPE_DATETIME_VARIATION_NORMAL);
What I would like, isn't simply an entire line on which the user has to write. I would like a thing like
Input: __/__/____
Where the user would have to complete with
Input: 18/04/2018
And then I would get the whole thing as a string: "18-04-2018"
What can I do?
You can parse the string to LocalDate then format to desired format, or you can just replace / with -:
String input = "18/04/2018";
String outPut;
// first approach
LocalDate localDate = LocalDate.parse(input, DateTimeFormatter.ofPattern("dd/MM/yyyy"));
outPut = localDate.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
// second approach
outPut = input.replaceAll("/", "-");
You have to use SimpleDateFormat which will change the format of date. have look this
public static String changeDateToTimeStamp(String date){
DateFormat inputFormat = new SimpleDateFormat("dd/mm/yyyy");
DateFormat outputFormat = new SimpleDateFormat("dd-mm-yyyy");
Date date1 = null;
try {
date1 = inputFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return outputFormat.format(date1);
}
this method will return date like "18-04-2018". Hope it will help you!

Android date format parse throwing an Unhandled Exception

I'm storing dates in a database as a single string in the format "2 15 2015" (presumably "M d yyyy"?). strDate in the code below contains the return value of a method that grabs the date. I want to parse the date so as to set a datepicker. Based on the examples in Java string to date conversion
I've created the following code for parsing the date, but am getting an "Unhandled Exception: java.text.ParseException" at
Date date = format.parse(strDate);
Scratching my head.
Calendar mydate = new GregorianCalendar();
String strDate = datasource.get_Column_StrVal(dbData,
MySQLiteHelper.dbFields.COLUMN_SPECIAL_DAYS_DATE);
SimpleDateFormat format = new SimpleDateFormat("M d yyyy", Locale.ENGLISH);
Date date = format.parse(strDate);
mydate.setTime(date);
You are getting this compile-time error because you are not handling the ParseException that the parse method throws. This is necessary because ParseException is not a runtime exception (it is a checked exception since it extends directly from java.lang.Exception).
You need to surround your code with try/catch to handle the exception, like this :
try {
SimpleDateFormat format = new SimpleDateFormat("M d yyyy", Locale.ENGLISH);
Date date = format.parse(strDate);
mydate.setTime(date);
} catch (ParseException e) {
//handle exception
}
Well, you indeed have it. Just surround it with try/catch as the compiler will hint you.

Java Unparseable Date difference in formats

How to differentiate between data-entry being (a) invalid date or (b) invalid format?
I have the following code for handling date inputs from an text file.
public boolean dateIsValid(String date) {
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
formatter.setLenient(false);
try {
Date dateParsed = (Date) formatter.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return false;
}
I have everything working as I want it to. The only problem I have is I am unable to differentiate the different parse exceptions thrown. For example:
if String date = 18/10/2012 --> java.text.ParseException: Unparseable date: "18/10/2012"
if String date = 2-12-2001 --> java.text.ParseException: Unparseable date: "2-12-2001"
As you can see, both the wrong formats throw the same error. How can I differentiate them so that I can handle them differently?
EDIT
To be more precise, in case of date 18/10/2012, I should throw an invalid date error and in the case of date 2-12-2001, I need to throw an invalid format exception. I dont need to handle different formats. I just need a way of getting different exceptions for these two different cases.
The issue seems to be at this line
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
For the first error it looks like that the date is coming first and the month later so it should be like
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Second error shows the incorrect format of the date supplied since it is containing - whereas you are expecting the format containing / ie like
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
If you want to handle different formats then try like this:
String[] formatDates= {"MM/DD/yyyy", "dd/MM/yyyy", "MM-dd-yyyy","dd-MM-yyyy"};
Date tryParse(String dateString)
{
for (String formatDate: formatDates)
{
try
{
return new SimpleDateFormat(formatDate).parse(dateString);
}
catch (ParseException e) {}
}
return null;
}
Unless you write code to parse the date strings yourself, you will not know why the format threw the exception.
I recommend a variation of the R. T. answer above.
Specifically, instead of creating a new formatter every time, create four (in that example) formatters at startup (in the constructor or in a static block).
I would use
public Date dateIfValid(String format, String date) {
DateFormat formatter = new SimpleDateFormat(format);
formatter.setLenient(false);
try {
return dateParsed = (Date) formatter.parse(date);
} catch (ParseException e) {
return null;
}
}
Date mmddyy = dateIfavlid("MM/dd/yy", date.replace("[^0-9]", "/"));
Date ddmmyy = dateIfavlid("dd/MM/yy", date.replace("[^0-9]", "/"));
if (mmddyy != null && ddmmyy == null) {
Note: this can be used to detect ambigous dates such as 01/02/03 which might be 3rd Feb 2001

How to convert time data in java?

The following time formats are in outlook calendar file
DTSTART;TZID="Eastern":20100728T140000
DTEND;TZID="Eastern":20100728T150000
how to convert this time to java time format.
This looks like iCalendar. Take a look at ical4j - a Java API for it.
Without tested, look at SimpleDateFormat
String ds = "DTSTART;TZID=\"Eastern\":20100728T140000";
Date d = new SimpleDateFormat("yyyyMMdd'T'HHMMSS").parse(ds.split(":")[1]);
Handling the timezone will be tricky as "Eastern" is not an actual timezone. However if you handle that, I would suggest the following SimpleDateFormat will handle the unadjusted parse for you.
Date unadjusted =
new SimpleDateFormat("yyyyMMdd'T'HHmmss").parse(line.split(":")[1]);
Another way using always SimpleDateFormat:
String[] strings = new String[]{"DTSTART;TZID=\"Eastern\":20100728T140000", "DTEND;TZID=\"Eastern\":20100728T150000"};
for (String string : strings) {
String dateString = string.replaceAll("(DTSTART|DTEND);TZID=\"Eastern\":", "");
dateString = dateString.replaceAll("T", "");
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
try {
Date date = sdf.parse(dateString);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
}

Categories