I'm making an alarm, get the current time as follows:
public String getAlarmTimeStringFive2db() {
String timef2db = "";
if (alarmTime.get(Calendar.HOUR_OF_DAY) <= 9)
timef2db += "0";
timef2db += String.valueOf(alarmTime.get(Calendar.HOUR_OF_DAY));
timef2db += ":";
if (alarmTime.get(Calendar.MINUTE) <= 9)
timef2db += "0";
timef2db += String.valueOf(alarmTime.get(Calendar.MINUTE));
return timef2db;
}
...
public static long create(Alarm alarm) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_ALARM_ACTIVE, alarm.getAlarmActive());
cv.put(COLUMN_ALARM_TIME, alarm.getAlarmTimeStringFive2db());
...
public void setAlarmTime(String alarmTime) {
String[] timePieces = alarmTime.split(":");
Calendar newAlarmTime = Calendar.getInstance();
newAlarmTime.set(Calendar.HOUR_OF_DAY,
Integer.parseInt(timePieces[0]));
newAlarmTime.set(Calendar.MINUTE, Integer.parseInt(timePieces[1]));
newAlarmTime.set(Calendar.SECOND, 0);
setAlarmTime(newAlarmTime);
}
...
This works fine, for example returns 5:35 ... all right.
My problem is I want to subtract 5 minutes always on time. If the time is 5:35, I want the alarm time starts at 5:30.
My problem is I do not know how to subtract those 5 minutes.
I tried
Calendar.MINUTE, Integer.parseInt(timePieces[1],5)
Calendar.MINUTE, -5)
...but nothing works
I read this link
Set Alarm To Alert 5 Minutes Before a certian Time
.. but I could not apply it to my code
Can anyone tell me as subtracting 5 minutes of my alarm?
thanks in advance
Regards
I'm not sure if you are using the Calendar instance in the right way, but here is an example shows that time changes when use add -5 to the current calendar
Calendar cal = Calendar.getInstance();
System.out.println("Before :" + cal.get(Calendar.MINUTE));
cal.add(Calendar.MINUTE, -5);
System.out.println("After :" + cal.get(Calendar.MINUTE));
and the result will be something like this:
Before :37
After :32
Related
I have the following code:
Calendar nextSchedule = Calendar.getInstance();
nextSchedule.set(Calendar.HOUR_OF_DAY, 0);
nextSchedule.set(Calendar.MINUTE, 0);
nextSchedule.set(Calendar.SECOND, 10);
nextSchedule.set(Calendar.MILLISECOND, 0);
nextSchedule.add(Calendar.DAY_OF_YEAR, 1);
Calendar cal = Calendar.getInstance();
long diff = nextSchedule.getTimeInMillis() - cal.getTimeInMillis();
long seconds = diff / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
As expected, around 11am it gave me 13/12hours but when doing the following in a widget:
Calendar nextSchedule = Calendar.getInstance();
nextSchedule.set(Calendar.HOUR_OF_DAY, 0);
nextSchedule.set(Calendar.MINUTE, 0);
nextSchedule.set(Calendar.SECOND, 10);
nextSchedule.set(Calendar.MILLISECOND, 0);
nextSchedule.add(Calendar.DAY_OF_YEAR, 1);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, nextSchedule.getTimeInMillis(), pendingIntent);
Around 1:30am, it was still not updated. Only somewhen between 2am and 9am (I was asleep) it got updated.
A similar strange thing happens elsewhere. I have a calendar view (applandeo) with the following code: cvCalendar.setOnDayClickListener(eventDay -> showDateItems(eventDay,lvCalendar));
private void showDateItems(EventDay eventDay, ListView lvCalendar) {
Calendar cal = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal.set(eventDay.getCalendar().get(Calendar.YEAR),eventDay.getCalendar().get(Calendar.MONTH),eventDay.getCalendar().get(Calendar.DATE));
cal2.set(eventDay.getCalendar().get(Calendar.YEAR),eventDay.getCalendar().get(Calendar.MONTH),1);
cal2.add(Calendar.MONTH, -1);
ArrayList<String> items = new ArrayList<>();
String line;
for (ItemsHistoryItem item: Utils.getInstance().itemsHistory) {
if (item.getxDay() < Utils.getInstance().calenderToEpoch(cal2) && item.getyDay() < Utils.getInstance().calenderToEpoch(cal2)) break;
if (item.getxDay() != Utils.getInstance().calenderToEpoch(cal) && item.getyDay() != Utils.getInstance().calenderToEpoch(cal)) continue;
line = item.getItemId() + ": $" + item.getAmount();
if (item.getxDay() == Utils.getInstance().calenderToEpoch(cal))
line += " (x day)";
else
line += " (y day)";
items.add(line);
}
ArrayAdapter<String> lcAdapter = new ArrayAdapter<>(requireActivity(), android.R.layout.simple_list_item_1, items);
lvCalendar.setAdapter(lcAdapter);
}
long calenderToEpoch(Calendar cal2) {
return TimeUnit.MILLISECONDS.toDays(cal2.getTimeInMillis());
}
Basically, the above code scans dates of items and when the user select a certain date, he gets a list of items which dates (x and y) are of that date. When doing so during the day, it works. When doing so in 1:30am (for example), it shifts one day ahead so if the user clicks on 12-oct, he gets the items of 11-oct. Somwhen between 2am and 9am it "shifts" back and works as expected.
Any idea what's wrong here?
I have a suggestion for using alarmmanager properly if you want it to fire exactly at the time you want else it does not fire on time when device is in deep sleep mode and gets delayed:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// use setAlarmClock function of AlarmManager
// but this function will show an alarm icon on statusbar
// if you dont want to show that icon you can use
// setExactAndAllowWhileIdle function but that will not be
// perfectly exact
}
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// use setExact function of AlarmManager
}
else {
// use set function of AlarmManager
}
Apparently the default timezone for Calendar.getInstance() in my case was GMT+3 so at 3am the items were shown for their dates and the widget was updated. to fix it, I simply did the following:
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
I have a method which takes two String parameters. the two strings are Time values in 24 hour format. The Times are picked using a TimePicker from UI.
The goal of the method is to get the duration between the StartTime and EndTime in Minutes.
public static String getTimeDuration(String StartTime24, String EndTime24)
{
String duration = "";
try
{
SimpleDateFormat parseFormat = new SimpleDateFormat("HH:mm");
Date startTime = parseFormat.parse(StartTime24);
Date endTime = parseFormat.parse(EndTime24);
long mills = endTime.getTime() - startTime.getTime();
long minutes = mills/(1000 * 60);
duration = "(" + minutes + " Minutes)";
}
catch(ParseException ex)
{
// exception handling here
}
return duration;
}
The method works fine if both the times are within a Single Date. For example:
StartTime = 22:15
EndTime = 23:51
Output = (96 Minutes)
But my problem is, the method returns negative if the end time is after 12'o clock at night. For example,
StartTime = 23:51
EndTime = 0:55
Output = (-1376 Minutes)
What I want: (64 Minutes)
How can get the duration correct ?
As there is no date used, you have to check first if your endTime is less than your startTime. If yes, then your endTime is on the next day and you have to add 1 day/86 400 000 milliseconds. Then you will have your desired result.
Just add this condition:
if(endTime.getTime() < startTime.getTime()){
long mills = ((endTime.getTime() + 86400000) - startTime.getTime()); 1 day = 86 400 000 mill
}
Hope this helps
You're only parsing the minutes and hours. There's no day on there. So that puts both times on the same day (the first day of the epoch, Jan 1 1970 to be exact). So the answer is correct. If you want it to treat the end time as the next day if its earlier than the start time, then add 1 day to the result (1440 minutes) if the result is less than 0.
I have developed an application where the user receives the message from other application user. I want to just show the time like Facebook, eg. 1sec ago or 3Hrs ago. Something in this fashion. I tried a code from one of our Fellow S.O expert but that code seems to misbehave.
Here's the code which i used in my app.
static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
static int[] steps = { 1, 60, 3600, 3600 * 24 };
static String[] names = { "sec", "mins", "hrs", "days" };
public static String formatDelay(String date) {
try {
Date d = sdf.parse(date);
Long stamp = d.getTime();
Calendar c = Calendar.getInstance();
Long now = System.currentTimeMillis() / 1000;
Format format = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
String time = format.format(now);
Long dif = now - stamp;
dif = dif / 1000;
if (stamp > now)
return "";
for (int i = 0; i < steps.length; i++) {
if (dif < steps[i]) {
String output = Long.toString(dif / steps[i - 1]) + " "
+ names[i - 1];
return output;
}
}
return Long.toString(dif / steps[3]) + " " + names[3];
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
When I used this code and sent a message from my application , it should show me sent 1sec ago, but in my case it shows me wrong time delay. For eg. I sent the message at 6pm then when I check my application sent item at 6:15pm its should show me 15 mins ago. But it shows me 12 hrs. When i debugged code, got to know that now time show date as 1970 00:00:00, this is because Long now = System.currentTimeMillis() / 1000; when i remove that /1000 it shows me correct date and time. I am clue less why this is happening please help.
Use
android.text.format.DateUtils.getRelativeTimeSpanString (long time, long now, long minResolution, int flags)
this will return time span in String format
For eg. if you pass a long value corresponding to 42 minutes ago in time and flags as DateUtils.FORMAT_ABBREV_RELATIVE the method will return 42 minutes ago
Official documentation DateUtils.getRelativeTimeSpanString
When you divide System.currentTimeMillis() by 1000 you are converting its value to seconds.
You're then using that value to create a date which is interpreting the seconds value as the milliseconds since Thu Jan 01 1970, hence the date difference.
I would recommend using Joda-Time API. See this answer for reference.
I want to calc the time differnce from when the user pressed start and stop.
This is what I got so far:
Done in not worker thread:
runTime = System.currentTimeMillis();
Done on main thread:
DateFormat formatter = new SimpleDateFormat("hh:mm:ss.SSS");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis() - runTime);
timeTextView.setText("Time: " + formatter.format(calendar.getTime()));
The result is always "01:00:00.000".
How come I get a 1hour added to the time?
And ofc I press the start and stop button faster then one hour.
The result you have is the time since epoch in java, So if you try to print
timeTextView.setText("Time: " + calendar.getTime().toString());
You are more likely to have the result of Wed Dec 31 19:00:00 EST 1969 depends on which TimeZone you currently are. From your code above I got 07:00:00:000 because I am at EST TimeZone. You cant really do about it but it eliminate the hh so it will only show the minutes, seconds, and milliseconds.
A simple way of solving (working around ?) this issue:
long startTime = System.currentTimeMillis();
//* do something
long endTime = System.currentTimeMillis();
long elapsedTimeInMilliSecs=(endTime - startTime);
Calendar ...
I use something like this and it works fine.
Try this if you just want your elapsed time in HH:MM:SS, this works even if you have more than 24 hours.
timeTextView.setText("Time: " + convertMillis(System.currentTimeMillis() - runTime));
...
public static String convertMillis(long milliseconds){
long time = milliseconds / 1000;
String seconds = Integer.toString((int)(time % 60));
String minutes = Integer.toString((int)((time % 3600) / 60));
String hours = Integer.toString((int)(time / 3600));
for (int i = 0; i < 2; i++) {
if (seconds.length() < 2) {
seconds = "0" + seconds;
}
if (minutes.length() < 2) {
minutes = "0" + minutes;
}
if (hours.length() < 2) {
hours = "0" + hours;
}
}
return(hours + ":" + minutes + ":" + seconds);
}
I'm setting a Time Object in Android. How do I set the AM and PM value at creation without relying on 24 hour time? For instance:
int hour = 7; // this returns 7am
//int hour = 19; this returns 7pm
myTime.set(second, minute, hour, day, month, year);
Log.i("TIME", "My time is: " + myTime);
It's not really clear what you're trying to do, but I suspect you want something like:
// Assume input of hour12 in range [1, 12] and isPM is a boolean
int hour24 = (hour12 % 12) + isPM ? 12 : 0;
That's assuming you want an hour of "12" and "AM" to mean midnight.
Then use hour24 when setting myTime.