Reputation: 5246
I want to calculate 1 month ago from current time in milliseconds. For example if date is 25.11.2016 then I want to get 25.10.2016 as milliseconds format. How can I calculate this date as milliseconds? Below code is not working properly I think.
System.currentTimeMillis() - 1000*60*60*24*30
Upvotes: 2
Views: 10036
Reputation: 14678
You can use this way:
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
c.add(Calendar.MONTH, -1);
long result = c.getTimeInMillis();
Note that System.currentTimeMillis() is using UTC, so you need to create an instance of Calendar using the same TimeZone.
Upvotes: 7
Reputation: 16158
With Java 8 you can do:
// Get the actual date time and subtract one month
LocalDateTime ldt = LocalDateTime.now().minusMonths(1);
// LocalDateTime cannot be directly converted to millis. It has no notion of a TimeZone, so:
ZonedDateTime zdt = ldt.atZone(ZoneId.of("America/Los_Angeles")); // Just insert the correct zone
// Now you can get the Millis:
System.out.println(zdt.toInstant().toEpochMilli());
Thanks to commenter @BasilBourque:
For Java 6 & 7, ThreeTen-Backport. Further adapted for Android in ThreeTenABP. Absolutely worth the bother of adding to you project and learning.
Upvotes: 3
Reputation: 350
Try this:
try {
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date past = format.parse("01/10/2010");
Date now = new Date();
System.out.println(TimeUnit.MILLISECONDS.toMillis(now.getTime() - past.getTime()) + " milliseconds ago");
System.out.println(TimeUnit.MILLISECONDS.toMinutes(now.getTime() - past.getTime()) + " minutes ago");
System.out.println(TimeUnit.MILLISECONDS.toHours(now.getTime() - past.getTime()) + " hours ago");
System.out.println(TimeUnit.MILLISECONDS.toDays(now.getTime() - past.getTime()) + " days ago");
} catch (Exception j) {
j.printStackTrace();
}
Upvotes: -1
Reputation: 963
I think this is what you need.
Calendar aMonthAgo = Calendar.getInstance();
aMonthAgo.add(Calendar.MONTH, -1);
long aMonthAgoInMS = aMonthAgo.getTime().getTime();
Upvotes: 2
Reputation: 6954
You can do in this way:
Date d = new Date();
Calendar c = new GregorianCalendar();
c.setTime(d);
c.add(Calendar.MONTH, -1);
Date dOneMonthAgo = c.getTime();
System.out.println("D: "+d+" dOneMonthAgo: "+dOneMonthAgo);
long todayMillis = d.getTime();
long oneMonthAgoMillis = dOneMonthAgo.getTime();
I hope this helps Angelo
Upvotes: 5