0

what is the correct value for the formula date()-day(date())+1?

if date() returns '2016/5/5'

is it, 2016/5/1? or 2016/4/29?

because when converting code from visual foxpro to java?

following code produces different result.

Calendar today2 = Calendar.getInstance();   

Calendar endDate = Calendar.getInstance();
endDate.add(Calendar.DATE, -1 * today2.get(Calendar.DATE)); 
endDate.add(Calendar.DATE, 1);  

above code produces 2016/5/1, while:

Calendar today2 = Calendar.getInstance();   
today2.add(Calendar.DATE, 1);   

Calendar endDate = Calendar.getInstance();
endDate.add(Calendar.DATE, -1 * today2.get(Calendar.DATE)); 

above code produces 2016/4/29.

not sure which conversion is correct?

vims liu
  • 643
  • 1
  • 9
  • 20

1 Answers1

1

Actually it is obvious and 2016/5/1. Math is simple:

date() - day(date()) would be 2016/5/5 - 5 days which is 2016/4/30 (theDate - day(theDate) gives last day of previous month, adding 1 gives first day of month that theDate is in). Adding 1 day to it means 2016/5/1.

I don't know Java, but to me your 2nd Java code is wrong.

In first one, you are subtracting day of month and then adding 1 (same as what VFP is doing).

In second one, you are setting today2 to "tomorrow", then subtracting tomorrow's day of month from today's date. Which would mean date() - (day(date()+1)) and you would get the day before last month's end date.

Update: I think you can simplify your code as:

Calendar today = Calendar.getInstance();   
today.add(Calendar.DATE, 1 - today2.get(Calendar.DATE)); 

IOW the VFP code to find start of a month:

firstDayOfMonth = theDate - day(theDate) + 1

should translate to:

Calendar firstDayOfMonth = Calendar.getInstance();
firstDayOfMonth.add(Calendar.DATE, 1 - firstDayOfMonth.get(Calendar.DATE));
Cetin Basoz
  • 22,495
  • 3
  • 31
  • 39
  • @vimsliu, although Cetin offers great detail / clarification in his answer, caution if you are actually dealing with a date/time field. If so, the adding of numeric, such as 1 is actually seconds to the date/time field, so to add 1 minute would be +60. 1 hour would be 60 * 60. But, you wanted by date and I just wanted to clarify IN CASE you were dealing with a date/time field. – DRapp Jul 13 '16 at 12:12
  • In case of a DateTime, start of month would be the same, you would cast it to a date and math remains the same :) cast(theDateTime as Date) - day(theDateTime) +1. – Cetin Basoz Jul 13 '16 at 14:03