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();
}
}
Related
I'm only getting this string "+0800" for a timezone from ihealth api. How can I get the corresponding java timezone id (like "US/Central") from this.
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("Z");
try {
Date date = sdf.parse("+0800");
cal.setTime(date);
System.out.println(cal.getTimeZone().getID());
} catch (Exception e) {
System.out.println("error" + e.getMessage());
}
but this always prints "Etc/UTC" which is not "+0800". what am I missing here?
The difficulty in what you are asking is that there are (almost?) always many timezone names associated with a given offset. So, for an offset of "+0800" we can do
int rawOffset = 8 * 3600000; // +0800 hours converted to milliseconds
String[] tzIds = java.util.TimeZone.getAvailableIDs(rawOffset);
for (String id : tzIds) {
System.out.println(id);
}
and see the list
Antarctica/Casey
Asia/Brunei
Asia/Choibalsan
Asia/Chongqing
Asia/Chungking
Asia/Harbin
Asia/Hong_Kong
Asia/Kashgar
Asia/Krasnoyarsk
Asia/Kuala_Lumpur
Asia/Kuching
Asia/Macao
Asia/Macau
Asia/Makassar
Asia/Manila
Asia/Shanghai
Asia/Singapore
Asia/Taipei
Asia/Ujung_Pandang
Asia/Ulaanbaatar
Asia/Ulan_Bator
Asia/Urumqi
Australia/Perth
Australia/West
CTT
Etc/GMT-8
Hongkong
PRC
Singapore
If you want "the corresponding java timezone id" (emphasis mine) then I guess you'll have to pick one. ;)
Provided you use Java 8 you can use ZoneOffset
For example
ZoneOffset zoneOffset = ZoneOffset.of("+0200");
TimeZone timezone = TimeZone.getTimeZone(zoneOffset));
Edit: ZoneOffset.of() accepts offsetId, which is different from the 4 digits representation, so this would not solve the problem.
Try this:
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("Z");
try {
Date date = sdf.parse("-0600");
cal.setTime(date);
System.out.println(sdf.format(date));
} catch (Exception e) {
System.out.println("error" + e.getMessage());
}
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();
}
How to compare two timeStamp and get the difference from those. I am trying to get the duration between two different timeStamps. Using Date, But i am getting exception while comparing.
This how I get the timeStamp 01-08-2013 06:19:35
I am getting exception like java.text.ParseException: Unparseable
date: "01-08-2013 06:19:35"
Convert the date into milliseconds and then you can use
long difference = finalDate.getTime() - initialDate.getTime();
Regarding your ParseException, there is something wrong with parsing pattern for your date formatter. I think this is the correct one "dd-MM-yyyy HH:mm:ss" if you want to parse "01-08-2013 06:19:35"
Joda-Time
Alternatively you can use the Joda-Time library and find the time difference in following way:
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MM-yyyy HH:mm:ss");
DateTime finalDate = formatter.parse("someDate1");
DateTime initialDate = formatter.parse("someDate2");
Interval interval = new Interval(finalDate, initialDate);
Calendar thatDay = Calendar.getInstance();
thatDay.set(Calendar.DAY_OF_MONTH,25);
thatDay.set(Calendar.MONTH,7); // 0-11 so 1 less
thatDay.set(Calendar.YEAR, 1985);
Calendar today = Calendar.getInstance(); //THIS IS TO GET TODAY DATE, you can simpy use your two dates
long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
Here's an approximation...
long days = diff / (24 * 60 * 60 * 1000);
PLUS : To Parse the date from a string, you could use
String strThatDay = "1985/08/25";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Date d = null;
try {
d = formatter.parse(strThatDay);//catch exception
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Calendar thatDay = Calendar.getInstance();
thatDay.setTime(d); //rest is the same....
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;
}
I try to subtract one day when the time inside 0:00 am - 12:00 am.
ex: 2012-12-14 06:35 am => 2012-12-13
I have done a function and It's work. But my question is any other better code in this case? Much simpler and easy to understand.
public String getBatchDate() {
SimpleDateFormat timeFormatter = new SimpleDateFormat("H");
int currentTime = Integer.parseInt(timeFormatter.format(new Date()));
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMdd");
String Date = dateFormatter.format(new Date());
if ( 0 <= currentTime && currentTime <= 12){
try {
Calendar shiftDay = Calendar.getInstance();
shiftDay.setTime(dateFormatter.parse(Date));
shiftDay.add(Calendar.DATE, -1);
Date = dateFormatter.format(shiftDay.getTime());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("BatchDate:", Date);
}
return Date;
}
THANKS,
Calendar shiftDay = Calendar.getInstance();
shiftDay.setTime(new Date())
if(shiftDay.get(Calendar.HOUR_OF_DAY) <= 12){
shiftDay.add(Calendar.DATE, -1);
}
//your date format
Use the Calendar class to inspect and modify the Date.
Calendar cal = new GregorianCalendar(); // initializes calendar with current time
cal.setTime(date); // initializes the calender with the specified Date
Use cal.get(Calendar.HOUR_OF_DAY) to find out the hour within the day.
Use cal.add(Calendar.DATE, -1) to set the date one day back.
Use cal.getTime() to get a new Date instance of the time that was stored in the calendar.
As with nearly all questions with regard to Date / Time, try Joda Time
public String getBatchDate() {
DateTime current = DateTime.now();
if (current.getHourOfDay() <= 12)
current = current.minusDays(1);
String date = current.toString(ISODateTimeFormat.date());
Log.d("BatchDate:" + date);
return date;
}