Time zones - how to? - android

The final goal is to convert a timestamp passed down from the server to local time.
Here's what I get:
2018-04-05T16:14:19.130Z
However, my local time is 11:14 AM CST. Here's what I've tried:
final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
final LocalTime localTime = formatter.parseLocalTime(text);
Timber.i(localTime.toString()); // output: 16:14:19.070
Output is: 16:14:19.070. Does anybody know how to use it? I expected to receive something like 11:14 AM.
Also, I've tried using this:
final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
final DateTime time = formatter.parseDateTime(text);
Timber.i(time.toString()); // output: 2018-04-05T16:14:19.490-05:00
Looks like it's a 5-hour difference there? Does anybody know how I can use this to convert to local time?

The "Z" in the end means that the date/time is in UTC. If you put it inside quotes, it's treated as a literal (the letter "Z" itself) and it loses this special meaning - you're basically throwing away the information that it's in UTC, and DateTime assumes the JVM default timezone (that's why your second attempt results in 16:14 in UTC-05:00).
DateTime can parse this input directly:
String input = "2018-04-05T16:14:19.130Z";
DateTime dt = DateTime.parse(input);
Then you convert this to the desired timezone. You can do:
dt = dt.withZone(DateTimeZone.getDefault());
Which will use your JVM's default timezone. But this is not so reliable, because the default can be changed at runtime - even by other applications running in the same JVM - so it's better to use an explicit timezone:
dt = dt.withZone(DateTimeZone.forID("America/Chicago"));
Then you can convert it to the format you want:
String time = dt.toString("hh:mm a"); // 11:14 AM
If you need to use a formatter, you can remove the quotes around "Z" and also set the timezone in the formatter:
DateTimeFormatter parser = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
// zone to be used for the formatter
.withZone(DateTimeZone.forID("America/Chicago"));
DateTime dateTime = parser.parseDateTime("2018-04-05T16:14:19.130Z");
String time = dateTime.toString("hh:mm a"); // 11:14 AM

Use this method to convert your time to local:
public static String convertTimeToLocal(String dateStr) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = format.parse(dateStr);
System.out.println(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String timeZone = Calendar.getInstance().getTimeZone().getID();
Date local = new Date(date.getTime() + TimeZone.getTimeZone(timeZone).getOffset(date.getTime()));
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
String reportDate = df.format(local);
return reportDate;
}
& for AM and PM, use this method:
public static String convertTimeToAmPm(String time) {
List<String> arr = Arrays.asList(time.split(":"));
int hours = Integer.parseInt(arr.get(0));
int mins = Integer.parseInt(arr.get(1));
String timeSet = "";
if (hours > 12) {
hours -= 12;
timeSet = "PM";
} else if (hours == 0) {
hours += 12;
timeSet = "AM";
} else if (hours == 12)
timeSet = "PM";
else
timeSet = "AM";
String minutes = "";
if (mins < 10)
minutes = "0" + mins;
else
minutes = String.valueOf(mins);
// Append in a StringBuilder
String aTime = new StringBuilder().append(hours).append(':')
.append(minutes).append(" ").append(timeSet).toString();
return aTime;
}

Related

How to Compare a Time with two other time provided?

Been confusing.. Like if we are comparing time, string is definitely not recommended... But if it is in the format of (HH:mm:ss). how should i compare them to do something?
For example:
Target1: 9:00:00
Target2: 23:00:00
how to do the logic for comparison where the input is larger than Target1 and smaller than Target2?
if(input > Target1 && input < Target2){
//do statement A
}else{
//do statement B
}
so if my input time is 10:00:00, it should run statement A
and if input time is 23:01:00, it should run statement B
how should i do that? is larger than (>) and smaller than (<) appropriate in time format?
Given them as string, you can convert them to a Date object from a SimpleDateFormat.
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
The easiest way is to convert them to the amount of milliseconds by doing
long time1 = sdf.parse(Target1).getTime();
long time2 = sdf.parse(Target2).getTime();
long inputTime = sdf.parse(input).getTime();
This way you are essentially doing a integer comparison, and you can forget about all the Date Time business.
if(inputTime > time1 && inputTime < time2)
SimpleDateFormat df=new SimpleDateFormat("hh:mm:ss");
Date d1=df.parse(dateToPars);
d1.after(otherTimeYouWantTocompare); OR
d1.before(otherTimeYouWantTocompare);
But you have to provide the time in the mentioned format
you can calculate diffrent using calender function .getTimeInMillis(), and get diffrent of 2 diffrent time , here you need to set only your specific time in Calender and make comparision with it
try{
Calendar calender = Calendar.getInstance();
Calendar calDb = Calendar.getInstance();
Calendar matchd = Calendar.getInstance();
mYear = calender.get(Calendar.YEAR);
mMonth = calender.get(Calendar.MONTH);
mDay = calender.get(Calendar.DAY_OF_MONTH);
mendYear = calDb.get(Calendar.YEAR);
mendMonth = calDb.get(Calendar.MONTH);
mendDay = calDb.get(Calendar.DAY_OF_MONTH);
// Here you can change day values
calDb.set(Calendar.DAY_OF_MONTH, mDay-1);
strbeforedate = mDateFormat.format(calDb.getTime());
curentdate = mDateFormat.format(calender.getTime());
calDb.setTime(mDateFormat.parse(strbeforedate));
calender.setTime(mDateFormat.parse(curentdate));
String mydate = "2013.03.14 03:11";
String mdatetime = "";
deletepath = new ArrayList<String>();
try{
// here your matching goes and pass date here
matchd.setTime(mDateFormat.parse(mdatetime));
long diff = calDb.getTimeInMillis() - calender.getTimeInMillis();
long matchdiff = matchd.getTimeInMillis() - calender.getTimeInMillis();
if(diff < matchdiff){
// do your work here
}else{
// do your else work here
}
}catch(Exception e){
e.printStackTrace();
}
}
}catch(Exception e){
e.printStackTrace();
}
}

How can i convert dropbox log timestamp?

I am debugging a android framework.
I pull out dropbox logs from device and it's created in /data/system/dropbox.
Log file name is printed like this format.
event_data#1362451303699
1362451303699 is timestamp and i want to change it like 05/03/2013 16:00 for legibility.
How can i convert this timestamp?
Is there any code needs to be changed?
Any help will be much appreciated.
use: Date date = new Date(timestamp);
Edit full code:
String wantedDate = "";
String log = "event_data#1362451303699";
int index = log.indexOf("#");
if(index != -1) {
index = index + 1; // skip # symbol
if(index < log.length()) { // avoid out of bounds
String logtime = log.substring(+1);
try {
long timestamp = Long.parseLong(logtime);
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date date = new Date(timestamp);
wantedDate = df.format(date);
} catch (NumberFormatException nfe) {
// not a number
}
}
}
if( ! "".equals(wantedDate) ) {
// everything OK
} else {
// error cannot retrieve date!
}
Related doc:
indexOf : http://developer.android.com/reference/java/lang/String.html#indexOf%28java.lang.String%29
SimpleDateFormat : http://developer.android.com/reference/java/text/SimpleDateFormat.html
you can use a SimepleDateFormat to parse it. For example:
long ts = 1362451303699;
Date date = new Date(ts);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
System.out.println(sdf.format(date));
With the SimpleDateFormat you can bring your Date in a more readable format.
It is a UNIX epoch timestamp, all you need to do is to convert the String representation of the number to long, then you can use it to create a Date object, which you can format with DateFormat. Something like this:
// Get this from the log
String timestamp = "1362451303699";
long epoch = Long.parseLong(timestamp);
Date date = new Date(epoch);
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm");
String formattedDate = format.format(date);

How do you compare the time portion of a time string?

I have in my preferences some strings that represent a start time and and ending time.
I wrote this function to determine if the current time is within the start and ending time. The format of the date strings is "HH:mm". The function takes the strings that are from the preferences.
I'm sure I'm missing some code for the comparing because my parsing returns a something like this:
Thu Sep 29 12:24:33 EDT 2011
But all I need is to get this:
12:24
Here is the function. Can you help me correct the coding?
Thanks.
Truly,
Emad
public static boolean currentTimeIsWithinStartAndEnd(String startTime,
String endTime) {
String pattern = "HH:mm";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
boolean booleanValueToReturn = false;
try {
Date startTimeToCompare = sdf.parse(startTime);
Date endTimeToCompare = sdf.parse(endTime);
/*
* These are for the current time in date format.
*/
Date currentTime = new Date(System.currentTimeMillis());
Log.w("Emad", "Current Time: " + currentTime + " Start Time is: "
+ startTimeToCompare + " End Time is : "
+ endTimeToCompare);
/*
* Check if current time is equal or greater than the start time.
*/
if (currentTime.compareTo(startTimeToCompare) == 0
|| currentTime.compareTo(startTimeToCompare) == 1) {
booleanValueToReturn = true;
/*
* Now check if the current time is equal or less than the end
* time.
*/
if (currentTime.compareTo(endTimeToCompare) == 0
|| currentTime.compareTo(endTimeToCompare) == -1) {
booleanValueToReturn = true;
} else {
booleanValueToReturn = false;
}
} else {
booleanValueToReturn = false;
}
} catch (java.text.ParseException e) {
}
return booleanValueToReturn;
You are using SimpleDateFormat Incorrectly.
String pattern = "HH:mm" should be format in which your input Date String is. otherwise how is SimpleDateFormat going to know which portion represents what.
Create two SimpleDateFormat, f1 (with Input String Format) and f2 ( with output String Format) ;
Use f1.parse() to get Date object for Input String.
Then use f2.format() on this Date Object to get Output String representation.
Refer to SimpleDateFormat for details on how to specify date Format.
public static boolean currentTimeIsWithinStartAndEnd(String startTime,
String endTime) {
// assuming input date string is of format MM/dd/yyyy. Change it according to your needs.
String inputPattern = "MM/dd/yyyy";
String outputPattern = "HH:mm";
SimpleDateFormat inputFormatter = new SimpleDateFormat(inputPattern);
SimpleDateFormat outputFormatter = new SimpleDateFormat(outputPattern);
Date startTimeToCompare = inputFormatter.parse(startTime);
String dateInRequiredFormat = outputFormat.format(startTimeToCompare);

Need get Time in a 24 hour format while adding Time

I had written a function for Adding time as given below
private void Delay15Minute() {
String pkManifest = manifest.pkManifestNo;
manifest_helper = new manifest_helper(this);
cursor = manifest_helper.GetDeliveries(pkManifest);
cursor.moveToFirst();
for (int i = 0; i < cursor.getCount(); i++) {
cursor.getString(cursor.getColumnIndex("PKDelivery"));
// String
// RevisedTime=cursor.getString(cursor.getColumnIndex("RevisedEstimatedDeliveryTime"));
String RevisedTime = "12:55";
// get hour and minute from time string
StringTokenizer st1 = new StringTokenizer(RevisedTime, ":");
int j = 0;
int[] val = new int[st1.countTokens()];
// iterate through tokens
while (st1.hasMoreTokens()) {
val[j] = Integer.parseInt(st1.nextToken());
j++;
}
// call time add method with current hour, minute and minutesToAdd,
// return added time as a string
String date = addTime(val[0], val[1], 15);
// Tioast the new time
Toast.makeText(this, "date is =" + date, Toast.LENGTH_SHORT).show();
}
}
public String addTime(int hour, int minute, int minutesToAdd) {
Calendar calendar = new GregorianCalendar(1990, 1, 1, hour, minute);
calendar.add(Calendar.MINUTE, minutesToAdd);
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
String date = sdf.format(calendar.getTime());
return date;
}
I am getting the oupt of this as 01:10 as 12 hours fromat...
I need to get it in 13:10 format ie 24 hour format.....Please help me
You used hh in your SimpleDateFormat pattern. Thats the 12 hour format. Use kk instead, that gives you the hours of the day in a 24 hour format. See SimpleDateFormat.
Simply create the instance of Calendar and get 24 hr time by,
Calendar c = Calendar.getInstance();
int Hr24=c.get(Calendar.HOUR_OF_DAY);
int Min=c.get(Calendar.MINUTE);
Use this code
long date = System.currentTimeMillis();
SimpleDateFormat date1 = new SimpleDateFormat("dd-MM-yyyy"); // for current date
SimpleDateFormat time1 = new SimpleDateFormat("kk:mm:ss"); // for 24 hour time
SimpleDateFormat time2 = new SimpleDateFormat("hh:mm:ss"); // for 12 hour time
String dateString = date1.format(date); //This will return current date in 31-12-2018 format
String timeString1 = time1.format(date); //This will return current time in 24 Hour format
String timeString2 = time2.format(date); //This will return current time in 12 Hour format
Log.e("TAG_1", "24 hour Time - " + timeString1);
Log.e("TAG_1", "24 hour Time - " + timeString1);
Log.e("TAG_1", "dd-MM-yyyy Date format - " + dateString);
than open your logcat to check result.

How can i get the time of a TimePicker in this format -> "08:00:00"?

i have a android timepicker, and i need to get his time in java code, and transform it into a string with this appereance: "08:00:00" (hours, mins, secs)
can someone help me to do it in a easy way?
code example will be appreciated
TimePicker t = new TimePicker(this);
String formattedTime = "";
int hour = t.getCurrentHour();
String sHour = "00";
if(hour < 10){
sHour = "0"+hour;
} else {
sHour = String.valueOf(hour);
}
int minute = t.getCurrentMinute();
String sMinute = "00";
if(minute < 10){
sMinute = "0"+minute;
} else {
sMinute = String.valueOf(minute);
}
formattedTime = sHour+":"+sMinute+":"+"00"; // Sorry you can't get seconds from a TimePicker
TimePicker has 2 methods available to get the set time. getCurrentHour and getCurrentMinute.
So outputting this as a string shouldn't be too hard.
String s;
Format formatter;
Calendar calendar = Calendar.getInstance();
// tp = TimePicker
calendar.set(Calendar.HOUR_OF_DAY, tp.getCurrentHour());
calendar.set(Calendar.MINUTE, tp.setCurrentMinutes());
calendar.clear(Calendar.SECOND); //reset seconds to zero
formatter = new SimpleDateFormat("HH:mm:ss");
s = formatter.format(calendar.getTime()); // 08:00:00
By the way, lowercase hh will get you a 12 hour clock.
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
String formatted = format.format(date); // date is a long in milliseconds
Just use SimpleDateFormat to format date and time .
Calendar cal=new Calendar();
SimpleDateFormat frmDate=SimpleDateFormat("dd-MM-yyyy");
String s=frmDate.format(cal.getTime());
SimpleDateFormat frmTime=SimpleDateFormat("HH:MM:SS");
String t=frmTime.formate(cal.getTime());
http://developer.android.com/reference/java/text/SimpleDateFormat.html
http://developer.android.com/reference/java/text/DateFormat.html
Also check out DateUtils, very useful.
Please find the below code:
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
String formatted = format.format(date); // date is a long in milliseconds

Categories

Resources