-1

I want to to get the elapsed time from the beginning of a month to now in android programmatically.

preferably using Calendar.getInstance().

For example today is 12/10/2018. so the duration in millisecs will be 12/01/2018 to 12/10/2018

Satish Shetty
  • 303
  • 2
  • 10

3 Answers3

2

To retrieve the beginning of the month:

val cal = Calendar.getInstance()
cal.set(Calendar.HOUR_OF_DAY, 0)
cal.clear(Calendar.MINUTE)
cal.clear(Calendar.SECOND)
cal.clear(Calendar.MILLISECOND)
cal.set(Calendar.DAY_OF_MONTH, 1)

Then to calculate elapsed in milliseconds:

val current = Calendar.getInstance()
val timePassedMilliseconds=current.timeInMillis-cal.timeInMillis
Alex
  • 9,102
  • 3
  • 31
  • 35
0

is your problem creating a new Calendar and populating it? you can create an empty one, and just populate with the fields that you are interested in.

Calendar now = Calendar.getInstance();

  Calendar startOfMonth = new GregorianCalendar();
    calendar.set(Calendar.DAY_OF_MONTH, 1); //first day of month
    calendar.set(Calendar.MONTH, now.get(Calendar.MONTH));
    calendar.set(Calendar.YEAR,  now.get(Calendar.YEAR);

  timeElapsed = now.getTimeInMillis() -  startOfMonth.getTimeInMillis() ;
Angel Koh
  • 12,479
  • 7
  • 64
  • 91
0

You can use calendar.set(year,month,1,0,0,0); to get the timestamp of the first day of the month.

Calendar calendar = Calendar.getInstance();
Date d = new Date(1544371200000L); //12/10/2018
calendar.setTime(d);     
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
calendar.set(year,month,1,0,0,0);
Date firstDayOfMonth = calendar.getTime();
long duration = d.getTime() - firstDayOfMonth.getTime();
Ricky Mo
  • 6,285
  • 1
  • 14
  • 30