I have time in seconds i want to convert it into a format like 6w 3d 9h 5m . Can someone please provide a method which can do this task. Thanks :)
w=weeks
d=days
h=hours
m=minutes
I have tried the below code but i dont get weeks using
int day = (int)TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds) - TimeUnit.SECONDS.toHours(TimeUnit.SECONDS.toDays(seconds));
long minute = TimeUnit.SECONDS.toMinutes(seconds) - TimeUnit.SECONDS.toMinutes(TimeUnit.SECONDS.toHours(seconds));
System.out.println("Day :"+day+" Hours :"+hours+" Minutes :"+minute);
this will give you:
1w 4d 10h 20m
there should be more elegant way, but this works:
long s = 987654l;
final long M=60,H=60*M, D=24*H, W=7*D;
long w = s/W;
s%=W;
long d = s/D;
s%=D;
long h = s/H;
s%=H;
long m = s/M;
System.out.printf("%dw %dd %dh %dm",w,d,h,m);
int seconds=98765410;
int weeks = (int) (TimeUnit.SECONDS.toDays(seconds) / 7);
int days = (int) (TimeUnit.SECONDS.toDays(seconds) - 7 * weeks);
long hours = TimeUnit.SECONDS.toHours(seconds) - TimeUnit.DAYS.toHours(days) - TimeUnit.DAYS.toHours(7*weeks);
long minutes = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds) * 60);
System.out.println(weeks+"w "+days+"d "+hours+"h "+minutes+"m");
Will print out:
163w 2d 2h 50m
Related
I check ical4j library. At time I need calculate event occurrences. Useful example to calculate is here. I try to shift start date and end date. In original start date is 20101113 - 2010 November, Saturday (it maps on pattern see BYDAY=...SA). I want do not care if start match or not. So I used start date with value 20101112 - 2010 November, Friday (it doesn't map on any day in pattern see BYDAY=MO,TU,SA)
VEvent event = new ContentBuilder().vevent {
dtstart('20101112', parameters: parameters() {value('DATE')})
dtend('20101113', parameters: parameters() {value('DATE')})
rrule('FREQ=WEEKLY;WKST=MO;INTERVAL=3;BYDAY=MO,TU,SA')
}
def dates = event.calculateRecurrenceSet(new Period('20101101T000000/20110101T000000'))
println dates
result is
[20101112T000000Z/20101113T000000Z, 20101113T000000Z/P1D, 20101129T000000Z/P1D, 20101130T000000Z/P1D, 20101204T000000Z/P1D, 20101220T000000Z/P1D, 20101221T000000Z/P1D, 20101225T000000Z/P1D]
almost as expected (except first period in result 20101112T000000Z/20101113T000000Z is redundant). So I continue investigate how to exclude one. In debug mode I see
result = {PeriodList#1497} size = 8
0 = {Period#2240} "20101112T000000Z/20101113T000000Z"
duration = null
rangeStart = {DateTime#2243} "20101112T000000Z"
rangeEnd = {DateTime#2244} "20101113T000000Z"
1 = {Period#2264} "20101113T000000Z/P1D"
duration = {Dur#2284} "P1D"
rangeStart = {DateTime#2285} "20101113T000000Z"
rangeEnd = {DateTime#2286} "20101114T000000Z"
2 = {Period#2265} "20101129T000000Z/P1D"
duration = {Dur#2284} "P1D"
rangeStart = {DateTime#2290} "20101129T000000Z"
rangeEnd = {DateTime#2291} "20101130T000000Z"
3 = {Period#2266} "20101130T000000Z/P1D"
duration = {Dur#2284} "P1D"
rangeStart = {DateTime#2295} "20101130T000000Z"
rangeEnd = {DateTime#2296} "20101201T000000Z"
4 = {Period#2267} "20101204T000000Z/P1D"
duration = {Dur#2284} "P1D"
rangeStart = {DateTime#2300} "20101204T000000Z"
rangeEnd = {DateTime#2301} "20101205T000000Z"
5 = {Period#2268} "20101220T000000Z/P1D"
duration = {Dur#2284} "P1D"
rangeStart = {DateTime#2315} "20101220T000000Z"
rangeEnd = {DateTime#2316} "20101221T000000Z"
6 = {Period#2269} "20101221T000000Z/P1D"
duration = {Dur#2284} "P1D"
rangeStart = {DateTime#2310} "20101221T000000Z"
rangeEnd = {DateTime#2311} "20101222T000000Z"
7 = {Period#2270} "20101225T000000Z/P1D"
duration = {Dur#2284} "P1D"
rangeStart = {DateTime#2305} "20101225T000000Z"
rangeEnd = {DateTime#2306} "20101226T000000Z"
Eureka! I've found marker to detect redundant dates in generated set (corrupted period has null duration). I continue handling it filtering periods with null value. But filter have filtered nothing. Continue checking...
package net.fortuna.ical4j.model;
...
public class Period extends DateRange implements Comparable<Period> {
private static final long serialVersionUID = 7321090422911676490L;
private Dur duration;
...
public final Dur getDuration() {
if (duration == null) {
return new Dur(getStart(), getEnd());
}
return duration;
}
...
as you can see, class Period has private Dur duration and public final Dur getDuration(). I can't access duration without workaround...
Question is
How should I do?
Use reflection hack to get duration - ugly solution.
Download library sources to change Period class and rebuild library - follows bad support new library versions.
Ask to ical4j developers to expand Period facade - it needs time to change and for release.
Use duration hack over toString (it's unreliable solution).
I've raised issue. I'will add details if they consider the issue.
I have block of code that allows me to retreive all the apps/services running on my android device including the app that I
am building. I am not entirely sure if I am on the right path butbecause I am debugging on android 4.3 I would like to use ActivityManager.RunningService.activeSince
(per service/app) and subtract it from SystemClock.elapsedRealtime(); which I understand is total milliseconds since reboot . So for example
if the device was rebboted at 10am and whatsapp was started at 10:15 and the current time is 1030 I want to be able to use these values
to get an a close estimate of the amount spent on whatsapp. I have a feeling that this is not the most elegant way to achieve this and I am therefore very open to
any advice. This my code below thus far . For now I am using android 4.3
ActivityManager am = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> services = am.getRunningServices(Integer.MAX_VALUE);
for (ActivityManager.RunningServiceInfo info : services) {
cal.setTimeInMillis(currentMillis-info.activeSince);
long millisSinceBoot = SystemClock.elapsedRealtime();
long appStartTime = info.activeSince;
long appDuration = appStartTime - millisSinceBoot ;
//long time = ((millisSinceBoot - values.get(position).activeSince)/1000);
//long time = ((millisSinceBoot - currentMillis-info.activeSince)/1000);
//Log.i("HRHHRHRHRHR", "%%%%%%%%%%%%%%%%"+time);
//String time1 = String.valueOf(time);
int seconds = (int) (appDuration / 1000) % 60 ;
int minutes = (int) ((appDuration / (1000*60)) % 60);
int hours = (int) ((appDuration / (1000*60*60)) % 24);
String time11 = hours+":"+minutes+":"+seconds;
Log.i("Time", "Secs:- " + seconds + " " + "Mins:- " + minutes + " " + "Hours:- " + hours);
Log.i(TAG, String.format("Process %s with component %s has been running since %s (%d milliseconds)",
info.process, info.service.getClassName(), cal.getTime().toString(), info.activeSince ));
}
I have tested below example before I do my exact task of converting Java Objects to JSON.
Converting Java objects to JSON with Jackson
And I was looking for the better performance (Converting time should be very less).
This article is showing the stats for the performance in between different APIs from this answer.
My finding was for example with the first link that I mentioned (with few records):
ValueData object = new ValueData();
List<ValueItems> information = new ArrayList<ValueItems>();
ValueItems v1 = new ValueItems(String.valueOf(Calendar.getInstance().getTimeInMillis()), "feat1", 1, "data1");
ValueItems v2 = new ValueItems(String.valueOf(Calendar.getInstance().getTimeInMillis()), "feat2", 2, "data2");
ValueItems v3 = new ValueItems(String.valueOf(Calendar.getInstance().getTimeInMillis()), "feat3", 3, "data3");
ValueItems v4 = new ValueItems(String.valueOf(Calendar.getInstance().getTimeInMillis()), "feat4", 4, "data4");
ValueItems v5 = new ValueItems(String.valueOf(Calendar.getInstance().getTimeInMillis()), "feat5", 5, "data5");
ValueItems v6 = new ValueItems(String.valueOf(Calendar.getInstance().getTimeInMillis()), "feat6", 6, "data6");
ValueItems v7 = new ValueItems(String.valueOf(Calendar.getInstance().getTimeInMillis()), "feat7", 7, "data7");
information.add(v1);
information.add(v2);
information.add(v3);
information.add(v4);
information.add(v5);
information.add(v6);
information.add(v7);
object.setInformation(information);
And I'm going to convert this object by using Jackson:
long smili = Calendar.getInstance().getTimeInMillis();
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);
long emili = Calendar.getInstance().getTimeInMillis();
System.out.println("taken time using jackson = " + (emili - smili) + " milli seconds");
And now I'm doing by using StringBuilder:
smili = Calendar.getInstance().getTimeInMillis();
StringBuilder sb = new StringBuilder();
sb.append("{\n\"information\" : [\n");
for (ValueItems vi : object.getInformation()) {
sb.append("{\n\"timestamp\" : \""+vi.getTimestamp()+"\",");
sb.append("\"feature\" : \""+vi.getFeature()+"\",");
sb.append("\"ean\" : "+vi.getEan()+",");
sb.append("\"data\" : \""+vi.getData()+"\"\n},");
}
sb.deleteCharAt(sb.length() - 1);
sb.append("]\n}");
emili = Calendar.getInstance().getTimeInMillis();
System.out.println("taken time using StringBuilder = " + (emili - smili) + " milli seconds");
I got the timing as given below just for the list size 7:
taken time using jackson = 534 milli seconds
taken time using StringBuilder = 1 milli seconds
I want to convert the object with the information list size more than 10k but the time should be very less.
Creating JSON buy using StringBuilder will help in this case?
Is there other API gives the facility that I require?
Please help me on this.
Thanks Sam B.
I have tried with jakson-afterburner:
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new AfterburnerModule());
ow = mapper.writer().withDefaultPrettyPrinter();
json = ow.writeValueAsString(object);
And I have tested with list sizes 7, 7000, 70000 and 700000:
timing was:
For 7:
taken time using jackson = 217 milli seconds
taken time using StringBuilder = 1 milli seconds
taken time using after-burner = 25 milli seconds
For 7000:
taken time using jackson = 310 milli seconds
taken time using StringBuilder = 31 milli seconds
taken time using after-burner = 65 milli seconds
For 70000:
taken time using jackson = 469 milli seconds
taken time using StringBuilder = 149 milli seconds
taken time using after-burner = 101 milli seconds
For 700000:
taken time using jackson = 1120 milli seconds
taken time using StringBuilder = 705 milli seconds
taken time using after-burner = 623 milli seconds
When the list size increases, afterburner is efficient.
I want to display the current cup usage and disk usage in two separate JProgressBars. And also it should update second by second. How to do it using java? I am quite new to java programming, so please give me some code example.
Thanks in advance.
You can use javasysmon-0.3.4.jar file to get the system related informations as CPU Usage,memory usage etc.
Some of the methods are listed below and if you want something else you can explore.
JavaSysMon monitor=new JavaSysMon();
//System.out.println("Operating System name is
"+monitor.osName());
long usersMillis = monitor.cpuTimes().getUserMillis();
/*System.out.println(String.format("User milli are %d days, %d
hr, %d min, %d sec",
TimeUnit.MILLISECONDS.toDays(usersMillis),
TimeUnit.MILLISECONDS.toHours(usersMillis),
TimeUnit.MILLISECONDS.toMinutes(usersMillis),
TimeUnit.MILLISECONDS.toSeconds(usersMillis)
));*/
long systemMillis = monitor.cpuTimes().getSystemMillis();
/*System.out.println(String.format("System milli are %d days, %d
hr, %d min, %d sec",
TimeUnit.MILLISECONDS.toDays(systemMillis),
TimeUnit.MILLISECONDS.toHours(systemMillis),
TimeUnit.MILLISECONDS.toMinutes(systemMillis),
TimeUnit.MILLISECONDS.toSeconds(systemMillis)
));*/
long idleMilli = monitor.cpuTimes().getIdleMillis();
/*System.out.println(String.format("Idle milli are %d days, %d
hr, %d min, %d sec",
TimeUnit.MILLISECONDS.toDays(idleMilli),
TimeUnit.MILLISECONDS.toHours(idleMilli),
TimeUnit.MILLISECONDS.toMinutes(idleMilli),
TimeUnit.MILLISECONDS.toSeconds(idleMilli)
));*/
/*CpuTimes time=new CpuTimes(usersMillis, systemMillis,
idleMilli);
cpuUsage=String.format("%.5f",
monitor.cpuTimes().getCpuUsage(time));*/
// System.out.println("CPU Usages "+String.format("%.5f",
monitor.cpuTimes().getCpuUsage(time)));
if(initialTime == null){
initialTime = monitor.cpuTimes();
}
cpuUsage = new
Float(monitor.cpuTimes().getCpuUsage(initialTime)).toString();
initialTime = monitor.cpuTimes();
long cpuUpTimeL = monitor.uptimeInSeconds()*1000;
float t = cpuUpTimeL/(float)(1000 * 60 * 60 * 24);
int days=(int) t;
t=t-days;
t= (t*24);
int hrs=(int) t;
t=t-hrs;
t=t*60;
int mins=(int) t;
t=t-mins;
t=t*60;
int secs=(int) t;
cpuUpTime=GetTotalTimeTakenInJourney.getTotalTimeTaken(days, hrs,
mins, secs);
// System.out.println("CPU Up time "+days+" days "+hrs+" hrs
"+mins+" mints "+secs+" seconds");
//System.out.println("CPU Numbers "+monitor.numCpus());
long totalBytes=monitor.physical().getTotalBytes();
totalRam=totalBytes/(float)(1024*1024*1024);
long freeBytes=monitor.physical().getFreeBytes();
freeRam=freeBytes/(float)(1024*1024*1024);
long ramUsages=totalBytes-freeBytes;
usedRam=ramUsages/(float)(1024*1024*1024);
You Could use tasklist command via this code
Runtime.getRuntime().exec(command)
My application executes the following code:
// Check intakes every 15 minutes
Intent i = new Intent(this, IntakeReceiver.class);
i.putExtra("TYPE", "TAKEIN_CHECK");
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), 0, i, 0);
AlarmManager am = (AlarmManager)(this.getSystemService(Context.ALARM_SERVICE));
Calendar cal = Calendar.getInstance();
int offset = 1000 * 60 * 15; // 1000 * 60 * 15 (15 minutes)
long nowLastRounded = cal.getTimeInMillis() - (cal.getTimeInMillis() % offset);
am.setRepeating(AlarmManager.RTC_WAKEUP, nowLastRounded + offset, offset, pi);
// Also set alarm for 11:50 every day to notify about low stock
Intent i2 = new Intent(this, LowStockReceiver.class);
i2.putExtra("TYPE", "STOCK_CHECK");
PendingIntent pi2 = PendingIntent.getBroadcast(getApplicationContext(), 1, i2, 0);
long interval_day = AlarmManager.INTERVAL_DAY;
long interval_hour = AlarmManager.INTERVAL_HOUR;
int offset2 = 1000 * 60 * 60 * 11 + 1000 * 60 * 50; // 11:50
final int tzOffset = TimeZone.getDefault().getOffset(System.currentTimeMillis());
offset2 -= tzOffset;
nowLastRounded = cal.getTimeInMillis() - (cal.getTimeInMillis() % interval_day);
am.setRepeating(AlarmManager.RTC_WAKEUP, nowLastRounded + offset2, interval_hour, pi2);
The problem is that the LowStockReceiver.onReceive() is called every 15 minutes (like the IntakeReceiver.onReceive()) but it should only be called every hour starting from 11:50.
I have checked the value of nowLastRounded + offset2 and it equals the local time today at 11:50 converted to GMT. So it should run at 11:50, 12:50, 13:50, etc. (just for testing purposes currently).
Anyone have any idea what I could be doing wrong?
Thank you!
Your using same id for pending intent for both the alarm.use different id.
Solved my own problem.
The problem was two-fold but the question didn't contain enough details for the question to be solvable:
Above code was called as a static function from the main Application class which could get instantiated by the first alarm.
This caused the second alarm to be rescheduled, and the time appeared to be in the past, causing it to be fired immediately and confusing me.