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.
Related
I need to convert a time stamp that currently is in string format "08.00" to a valid time in java so I later can compare time. How do I convert this string to time?
Something like this
DateFormat sdf = new SimpleDateFormat("hh:mm");
Date date = sdf.parse(time);
Instead of using the Date and/or SimpleDateFormat classes, perhaps consider LocalTime
String time = "08:00";
LocalTime lt = LocalTime.parse(time);
System.out.println(lt);
Output:
08:00
And can compare to other times easily with LocalTime::isBefore() or LocalTime::isAfter()
Example
Try below code,
String time = "08.00";
try {
DateFormat sdfInput = new SimpleDateFormat("hh.mm");
Date date = sdfInput.parse(time);
DateFormat sdfOutput = new SimpleDateFormat("hh:mm");
Log.e( "Time: ", sdfOutput.format(date));
} catch (Exception e) {
e.printStackTrace();
}
Output -> Time: 08:00
The easiest way to do so is with a SimplDateFormatter:
DateFormat sdf = new SimpleDateFormat("hh:mm")
Then you can call Date date = sdf.parse(*your time string*)
Now you have your time as a valid Date object.
I have timeformat like this hhmmss="151918"
so you can use any format instead of hhmmss according to your current time format like
"hh.mm" or hh:mm:ss etc
and you can call this method form any where you needed.
fun convertTimeFormat(time:String):String{
var formattedTime=""
try {
val inputFormat: DateFormat = SimpleDateFormat("hhmmss")
val timeObj = inputFormat.parse(time)
Log.d("timeObj",""+timeObj)
formattedTime=SimpleDateFormat("hh:mm aa").format(timeObj)
} catch (e: ParseException) {
e.printStackTrace()
}
return formattedTime
}
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!
Hi can anyone help please? I am trying to format a date and time string.
Currently it looks like this "20160112T110000Z" and I need it to be "2016-01-12T11:00:00Z"
The string without the special characters are returned from a 3rd party recurrence library. I need to convert it to have the special characters before parsing it to a Calendar object.
Can anyone help please?
The code that I have so far looks like:
final String TIMEFORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
String string = "20160112T110000Z";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date date = format.parse(string);
System.out.println(date);
However this just does not work.
Any suggestions are appreciated
You have to read the string with a format matching the source, this gives you a correct Date.
Then simply write it with the format you want :
String string = "20160112T110000Z";
String originalStringFormat = "yyyyMMdd'T'HHmmss'Z'";
String desiredStringFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'";
SimpleDateFormat readingFormat = new SimpleDateFormat(originalStringFormat);
SimpleDateFormat outputFormat = new SimpleDateFormat(desiredStringFormat);
try {
Date date = readingFormat.parse(string);
System.out.println(outputFormat.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
try this
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
// you can change format of date
Date date = formatter.parse(strDate);
Timestamp timeStampDate = new Timestamp(date.getTime());
return timeStampDate;
I am retrieving data from a webservice that provides a timestamp in the form of HH:mm:ss I am using SimpleDateFormat to convert this string into a date object then change its timezone if needed and also convert it from 24hour to 12 hour time.
Problem: When a time is fed in for 12am it looks like this 00:00:00
so 12:05 is 00:05:00
When i get the results they look like this.
times fed in 22:00:00 to 00:01:00
times retrieved 10:00 pm to 0:01 am
I have been looking around to see if there is a way to fix it but i feel like i will need to make a special case and parse the string myself if it has a 0 in the hours place.
Any help would be greatly appreciated.
public String parseTime(String time) {
String mTime = null;
TimeZone thisTimeZone = TimeZone.getDefault();
TimeZone ourTimeZone = TimeZone.getTimeZone("America/Los_Angeles");
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss", Locale.US);
SimpleDateFormat sdfThisTimeZone = new SimpleDateFormat("K:mm:a",
Locale.getDefault());
Date date = null;
sdfThisTimeZone.setTimeZone(thisTimeZone);
sdf.setTimeZone(ourTimeZone);
try {
date = sdf.parse(time);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mTime = sdfThisTimeZone.format(date.getTime());
//**********************************New: Does Not Work********************************
DecimalFormat nft = new DecimalFormat("00"); mTime = nft.format(mTime);
//**********************************New **********************************************
return mTime;
}
I have tried the line using DecimalFormat but i just copied it into the code for now to see if it would work. Unfortunately it made my app crash. The code that i have posted is executed inside an Async Task so i am not sure if that makes any difference but still thankyou for your help. Eventually i will solve this. But for now it is such a small detail that only occurs for 1 hour at 12am that i am moving on to bigger issues. If anyone can shed some light on this that would be awesome.
String getConvertedDateTime (String dateTime) {
String convertedDateTime = dateTime;
if (convertedDateTime != null
&& !convertedDateTime.equalsIgnoreCase("")
&& !convertedDateTime.equalsIgnoreCase("null")) {
try {
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
Calendar calendar = Calendar.getInstance();
java.util.Date convertedDate = formatter
.parse(convertedDateTime);
formatter.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
convertedDateTime = formatter.format(convertedDate.getTime());
} catch (Exception e) {
e.printStackTrace();
}
}
return convertedDateTime;
}
In mysql, i have a field time_entered of type datetime (sample data: 2012-06-20 16:00:47). I also have a method, getTimeEntered(), that returns the value as String. I want to display the date in this format 2012-06-20 using DateTimeFormat from GWT.
here's my code:
String date = aprHeaderDW.getTimeEntered();
DateTimeFormat fmt = DateTimeFormat.getFormat("MM-dd-yyyy");
dateEntered.setText("" + fmt.format(date));
The problem is, the format method doesn't accept arguments as String. So if there's only a way I could convert the date from String to Date type, it could probably work. I tried typecasting but didn't work.
You should be able to just use DateTimeFormat.
Date date = DateTimeFormat.getFormat("yyyy-MM-dd HH:mm:ss").parse("2012-06-20 16:00:47");
String dateString = DateTimeFormat.getFormat("yyyy-MM-dd").format(date);
Otherwise there is a light-weight version of SimpleDateFormat that supports this pattern.
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2012-06-20 16:00:47");
Hi There are two options.
The first is as it is already a string you could use a regular expression to modify the format.
The second is using a SimpleDateFormater you can parse the string to a date then back again.
For example:
public class DateMerge {
public static void main(String arg[])
{
String out = dateConvert("2012-06-20 16:00:47");
System.out.println(out);
}
public static String dateConvert (String inDate)
{
try {
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
date = (Date)formatter.parse(inDate);
formatter = new SimpleDateFormat("dd-MM-yyyy");
String outDate = formatter.format(date);
return outDate;
} catch (ParseException e)
{System.out.println("Exception :"+e); }
return null;
}
}
You may use like this.
String date = "2012-06-20 16:00:47";
SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
String lDate=sf.format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date));
System.out.println(lDate);
Output:
2012-06-20
After trying a lot of times I came up with a solution, based on #Keppil and adding my own code.
Here's Keppil's suggested solution for converting String datetime into Date type:
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2012-06-20 16:00:47");
...but my second requirement is to display just the date like 2012-06-20. Even though I removed HH:mm:ss, it still displayed the time like this 2012-06-20 00:00:00.
Here's my final solution:
Date date = null;
String d = rs.getString(SQL_CREATION_TIME); // assigns datetime value from mysql
// parse String datetime to Date
try {
date = new SimpleDateFormat("yyyy-MM-dd").parse(d);
System.out.println("time entered: "+ date);
} catch (ParseException e) { e.printStackTrace(); }
// format the Date object then assigns to String
Format formatter;
formatter = new SimpleDateFormat("yyyy-MM-dd");
String s = formatter.format(date);