all my code is in timer and it tik every 2 seconds
I have 3 different times
1) Time from the time picker(sTime).
2) Get Current time of my phone(cTime).
3) Expiry Time - (for creating range between timepicker's time and expiry time) (rTime).
I want to silent my phone when cTime is equal or after sTime
and turn back my phone profile to normal when cTime is equal or after rTime
but i cannot achieve this. i have done my coding and i think logic is fine but why its not working. please help me in this regard.
Here is my code
AudioManager am;
am = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
try {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String savedTime = sHour + ":" + sMin;
Date sTime = sdf.parse(savedTime);
Calendar c = Calendar.getInstance();
int currentHour = c.get(Calendar.HOUR);
int currentMin = c.get(Calendar.MINUTE);
String currentTime = currentHour + ":" + currentMin;
Date cTime = sdf.parse(currentTime);
int rangeHour = sHour;
int rangeMin = sMin + 1;
Date rTime = sdf.parse(rangeHour + ":" + rangeMin);
if (cTime.after(sTime)) {
am.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
Log.e("res", "Silent Mode Timing");
}
if (cTime.after(rTime)) {
am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Log.e("res", "Normal Mode Timing");
}
} catch (Exception ex) {
Log.e("res", ex.toString());
}
Ok, I have a suggestion. The method 'after' of Date class compare two long values in milliseconds. When you get current time milliseconds value it calculate as current year + current month + current day and hour etc. (or something like this). And when you get milliseconds of you savedTime it calculates incorrect because you not specify full Date (year, etc). I mean that you startTime incorrect when it convert in long milliseconds value in Date.after method. try to change you algorithm to work wit long timestamp, not with Date. for example current time is System.currentTimeMillis(). I hope it help. Sorry for my English
Ok, try to use something like this:
private void compareTime(final String year, final String day, final String hour, final String month, final String minutes) {
AudioManager am;
am = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
final SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:dd:mm:yy");
final String savedTimeValue = hour + ":" + minutes + ":" + day + ":" + month + ":" + year;
try {
final Date savedDate = sdf.parse(savedTimeValue);
final long savedTime = savedDate.getTime();
final long currentTime = System.currentTimeMillis();
final long rangeTimeMilliseconds = 1 * 60 * 1000; // 1 minute in milliseconds
if (currentTime > savedTime) {
am.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
}
if (currentTime > rangeTimeMilliseconds) {
am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
}
}catch(Exception e) {
e.printStackTrace();
}
}
Related
I have an app where the user gets a task every day so what is the best method to use to keep track of time for a period of a day including any system condition even if the user turned his phone off.
I found a suggestion to use SystemClock.elapsedRealTime() but it doesn't include the phone being turned off ... so any other suggestions ?
Try to save (in SharedPreferences for example) the time of getting the task. Then when you want to get the period from this time to now you can do something like this:
long milliSecondsTriggering -> the milliseconds of the time of triggering the event;
long milliSecondsCurrentTime -> current time in milliseconds;
long periodSeconds = (milliSecondsCurrentTime - milliSecondsTriggering ) / 1000;
long elapsedDays = periodSeconds / 60 / 60 / 24;
try this method once:
call this method by passing long value of your time
public static String getDateDifferenceInDays(long timeInMillis) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MM yyyy");
SimpleDateFormat simpleDateFormatParse = new SimpleDateFormat("dd MM yyyy");
Date serverDate = new Date(timeInMillis * 1000L);
Date localDate = new Date();
String strDay = "";
try {
Date dateServer = simpleDateFormatParse.parse(simpleDateFormat.format(serverDate));
Date dateLocal = simpleDateFormatParse.parse(simpleDateFormat.format(localDate));
long diff = dateServer.getTime() - dateLocal.getTime();
//Log.d(TAG, "server date-----" + dateServer + "-----local date----" + dateLocal);
long days = diff / (24 * 60 * 60 * 1000);
//long days = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
if (days >= 0) {
strDay = "Days left - " + days;
} else {
strDay = "Time elapsed";
}
} catch (ParseException e) {
e.printStackTrace();
}
return strDay;
In my application i should show hour and minute and i get this numbers from server with this sample :
Json :
{
data:{
time:84561
}
}
i should get this number from time and show it with this format
**hh : mm : ss**
I can get number of time, but i can't convert this to **hh : mm : ss** .
How can i it?
long timeSec= 84561;// Json output
int hours = (int) timeSec/ 3600;
int temp = (int) timeSec- hours * 3600;
int mins = temp / 60;
temp = temp - mins * 60;
int secs = temp;
String requiredFormat = hours+ ": "+mins+": "+secs;//hh:mm:ss formatted string
Java 9 answer
Duration time = Duration.ofSeconds(87561);
String hms = String.format("%02d : %02d : %02d",
time.toHoursPart(),
time.toMinutesPart(),
time.toSecondsPart());
Unfortunately in Java 8 Duration does not lend itself well to formatting. The methods I use in the snippet are introduced in Java 9 and will calculate the values for hh, mm and ss. Then String.format() does the rest.
I know you cannot use this on Andriod (yet), but I wanted to have this answer stand here for others who can use Java 9, now or in the future.
Very simple
If this is unix time then it will be converted into human readable time format with this snippet.
String relavtiveTimeString = String.valueOf(DateUtils.getRelativeTimeSpanString(unixTime));
You can use new Date(unix); and with below function you can get formatted date. You can format in different style.
//This mehtod convert the date into standard date like : 2017-12-23
public static String getformateDate(Date dateObject) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
return dateFormat.format(dateObject);
}
For more information check this link already answer :
Convert unix time stamp to date in java
Referance:
https://developer.android.com/reference/android/text/format/DateUtils.html
https://developer.android.com/reference/android/text/format/Time.html
Pass your Number or timestamp and convert to milliseconds for hour and minute.use the below code.
public static String getCurrentTimeStamp(String mCurrentTime) {
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy hh:mm a z");
TimeZone tz = TimeZone.getDefault();
format.setTimeZone(tz);
// System.out.println("TimeZone "+tz.getDisplayName(false, TimeZone.SHORT)+" Timezon id :: " +tz.getID());
SimpleDateFormat dateParser = new SimpleDateFormat("dd/MM/yyyy hh:mm a z");
Date dateTime = null;
try {
dateTime = dateParser.parse(format.format(Long.parseLong((mCurrentTime)) * 1000));
Log.e("Starttime", "Starttime" + format.format(dateTime));
return format.format(dateTime);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
Try This Logic Use it As per Requirement
public class Test {
public static void main(String[] args) {
String json = "{\n" +
" data:{\n" +
" time:84561\n" +
" }\n" +
"}";
Date date = new Gson().fromJson(json, Date.class);
long milli = date.getTime() * 1000;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
System.out.println(simpleDateFormat.format(new java.util.Date(milli)));
}
class Date implements Serializable{
int time;
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
}
Output
05:30:00
If you want to download Gson jar download it from
here
Good day.I am building an chat application.For purpose i decided to put a date of message had been sent.No wounder that in different countries the date must show different.For example let's take 2 different countries and assume the difference between them are 2 hours.CountryX and CountryY.The user send message from CountryX which time is lets say 15:00.I am saving this on server with exact timezone time as user sent,exactly 15:00 as CountryX.Second user receives the message in CountryY which is more in 2 hours from CountryX,so basically The time which I MUST show in CountryY must be 17:00.This is the issue.How can i convert an already received time with known timezone to local in order to show correct?I did google a lot but all i came up,were solutions where you would simply just get an time for exact country,and not convert the CountryX sent Time to CountryY local time to show it correctly in CountryY.Please can you provide an help?Thank you very much beforehand.
For everyone suffering because of this.I have ended up creating my own class with my own logic and it works flawlessly and as an extra bonus couple of handy methods with time
public class Time {
public static String getCurrentTime() {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
String finalFormat = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
if (month < 10) {
String finalMonth = "0" + month;
finalFormat = year + "-" + finalMonth + "-" + day + " " + hour + ":" + minute + ":" + second;
}
return finalFormat;
}
public static String convertToLocalTime(String timeToConvert) {
SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sourceFormat.setTimeZone(TimeZone.getTimeZone(Constants.SERVER_TIME_ZONE));//where server time zone is the time zone of your server as defauul,E.X -America/Los_Angeles
Date parsed;
try {
parsed = sourceFormat.parse(timeToConvert);
} catch (ParseException e) {
e.printStackTrace();
return "";
}
TimeZone tz = TimeZone.getDefault();
SimpleDateFormat destFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
destFormat.setTimeZone(tz);
String result = destFormat.format(parsed);
return result;
}
public static String getTimeZone() {
return TimeZone.getDefault().getID();
}
}
I am given a unix timeStamp and I need to calculate the difference between current time and the given unix timestamp like:
2 sec ago
5 mins ago
2 hours ago
3 days ago
So I have written below code:
String time = "given unix timeStamp";
Date date = new Date();
date.setTime(Long.parseLong(time) * 1000);
Calendar start = Calendar.getInstance();
start.setTime(date); // given time
Calendar end = Calendar.getInstance();
end.setTime(new Date()); // current time
Integer[] elapsed = new Integer[6];
Calendar clone = (Calendar) start.clone();
elapsed[0] = elapsed(clone, end, Calendar.YEAR);
clone.add(Calendar.YEAR, elapsed[0]);
elapsed[1] = elapsed(clone, end, Calendar.MONTH);
clone.add(Calendar.MONTH, elapsed[1]);
elapsed[2] = elapsed(clone, end, Calendar.DATE);
clone.add(Calendar.DATE, elapsed[2]);
elapsed[3] = (int) (end.getTimeInMillis() - clone.getTimeInMillis()) / 3600000;
clone.add(Calendar.HOUR, elapsed[3]);
elapsed[4] = (int) (end.getTimeInMillis() - clone.getTimeInMillis()) / 60000;
clone.add(Calendar.MINUTE, elapsed[4]);
elapsed[5] = (int) (end.getTimeInMillis() - clone.getTimeInMillis()) / 1000;
submissionTime.setText(elapsed[0] + " years," + elapsed[1] + " months,"
+ elapsed[2] + " days," + elapsed[3] + " hours," + elapsed[4]
+ " minutes," + elapsed[5] + " seconds");
And this is the elapsed() function:
public static int elapsed(Calendar before, Calendar after, int field) {
Calendar clone = (Calendar) before.clone();
int elapsed = -1;
while (!clone.after(after)) {
clone.add(field, 1);
elapsed++;
}
return elapsed;
}
But this is giving me wrong input. I am new in Java/Android date manipulation and some full working code will be helpful.
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.