Parsing time string and changing timezone - java

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;
}

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.

Convert only time part in android from string to time

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
}

Java : calculate remaining time compared to current time

I have a string in format :
2015-10-01 02:00
I want to print the remaining time compared to current time in Java, it should print in format :
It remains 1 day 4 hours 25 minutes
How could I do that ? Thanks for any ideas.
I got it working! Could you withdraw all the unvotes please ?
public static void calculateRemainTime(String scheduled_date){
// date format
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
// two dates
java.util.Date scheduledDate;
Calendar current = Calendar.getInstance();
java.util.Date currentDate;
String current_date = format.format(current.getTime());
try {
scheduledDate = format.parse(scheduled_date);
currentDate = format.parse(current_date);
long diffInMillies = scheduledDate.getTime() - currentDate.getTime();
long diffence_in_minute = TimeUnit.MINUTES.convert(diffInMillies,TimeUnit.MILLISECONDS);
System.out.println(diffence_in_minute);
} catch (ParseException e) {
e.printStackTrace();
}
}

Convert UTC time to local time java Android

Im retrieving some values from a json service and the retrieved datetime values are stored in UTC format.
i've tried a lot of sample codes to convert the datetime values to user local timezone but im still getting the same value after conversion.
This is what i have actually: (copied from other posts)
String sJsonDate = "2015-07-08T12:08:13.0625+00:00";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
Date localDateTime = simpleDateFormat.parse(sJsonDate);
} catch (ParseException e) {
e.printStackTrace();
}
The result value (localDateTime) is the same as the original value.
I am in Paraguay (GMT-4) and the resulting values needs to be minus one hour diference, like this: ("2015-07-08 07:13:25") (The values are stored in Argentina)
Help please!
I've found the solution, we are using day light savings so i had to disccount one hour to the resulting datetime.
So, i share the code for someone else:
public Date getDateInTimeZone(Date currentDate, String timeZoneId) {
TimeZone timeZone = TimeZone.getTimeZone(timeZoneId);
Date localDateTime = new Date(currentDate.getTime() + timeZone.getOffset(currentDate.getTime()));
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(localDateTime.getTime());
if (timeZone.useDaylightTime()) {
// time zone uses Daylight Saving
cal.add(Calendar.MILLISECOND, timeZone.getDSTSavings() * -1);// in milliseconds
}
return cal.getTime();
}
Usage:
String sDate = "2015-07-08T12:08:13.0625+00:00";
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date theDate = simpleDateFormat.parse(sDate);
Date localDateTime = getDateInTimeZone(theDate, TimeZone.getDefault().getID());
} catch (ParseException e) {
e.printStackTrace();
}

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