How to calculate number of days between Calendar objects
Hi,
I need to calculate the number of days between two Calendar objects. Here is some sample code:
Calendar now = Calendar.getInstance();
now.set(Calendar.HOUR_OF_DAY, 0);
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
now.set(Calendar.MILLISECOND, 0);
// get a calendar that represents a day in the past
Calendar aDayInThePast = getADayInThePast();
aDayInThePast.set(Calendar.HOUR_OF_DAY, 0);
aDayInThePast.set(Calendar.MINUTE, 0);
aDayInThePast.set(Calendar.SECOND, 0);
aDayInThePast.set(Calendar.MILLISECOND, 0);
// how can I calculate the number of days ago this was??
//it would also be useful to get back a negative number if the day is in the future
My favorite answer so far is reply 15 by Marc__: http://forum.java.sun.com/thread.jspa?threadID=488668&start=15
Similar Messages
-
How to calculate number of days between fixed date and hire date in schema
i want to calculate the number of days between a fixed date en the hire date (infotype 041)
If i read the documentation right, i should use the following command:
HRS=YDXA02
Variable 3 (the x) is the fixed data.
My question is how do i program the variable x?
Let's say the date 01.01.2008
Any help would be welcomeI assume we are talking about PCR for payroll. In this case look at documentation for operation NUM:
OOOOOO
Xnnnnn
X Table
nnnnn Table field
nn Date type 'nn' from the Date Specifications infotype (0041)
Date types are taken from table T548Y.
Your operation would look like:
NUM=Faaesb
F Fixed indicator for deadline calculation
aa Date type: Start date of period to be
calculated; if the date type is not 'nn,'
the second position is left blank.
e Unit, in which the duration is calculated:
T = days
W = week
s End date of period to be calculated:
(blank) End of current payroll period
J End of current calendar year
A Start of current calendar year
B Start of WPBP period
No other specifications are possible.
So it depends on what kind of fixed date you need.
Hope it helps,
Carlos. -
How to calculate number of days between two date in Template design?
Hello guys
I have a situation where I have to create a template that returns data, and one of the thing of the existing report is that there is a column that is actually the number of days between start date and end date columns..
So in template, how would I be able to do the same? I have start date and end date columns on the template, now when I created another column using expression like end date - start date and preview the template, I am getting errors saying :
Caused by: oracle.xdo.parser.v2.XPathException: Cannot convert 03/31/2009 to number.
at oracle.xdo.parser.v2.XSLStylesheet.flushErrors(XSLStylesheet.java:1534)
at oracle.xdo.parser.v2.XSLStylesheet.execute(XSLStylesheet.java:521)
at oracle.xdo.parser.v2.XSLStylesheet.execute(XSLStylesheet.java:489)
at oracle.xdo.parser.v2.XSLProcessor.processXSL(XSLProcessor.java:271)
at oracle.xdo.parser.v2.XSLProcessor.processXSL(XSLProcessor.java:155)
at oracle.xdo.parser.v2.XSLProcessor.processXSL(XSLProcessor.java:192)
Please advice
ThanksHi
There is an extension function you can use, from the javadoc:
date_diff
public static long date_diff(java.lang.String format,
java.lang.String fromDate,
java.lang.String toDate,
java.lang.String locStr,
java.lang.String tzID)
Method to get the difference between two dates in the given locale. The dates need to be in "yyyy-MM-dd" format. This function supports only Gregorian calendar.
Parameters:
format - the format to which the difference is required; allowed formats are y (for Year), m(for month), w(for week), d(for day), h(for hour), mi(for minute), s(for seconds) and ms(for milliseconds)
fromDate - the first date
toDate - the second date
locStr - locale string -> lang-Territory
tzID - timezone ID ->http://java.sun.com/j2se/1.4.2/docs/api/java/util/TimeZone.html
Returns:
the difference in dates in the desired format
For example
<?xdoxslt:date_diff(‘d’,’2009-09-14’, ‘2009-09-20’,’en-US’,1)?>
give a result of 6
You can substitute in columns for the dates, just remember the date format required.
Regards
Tim -
Hello -
I've been tearing my hair out over this problem i'm trying to solve, probably just been staring at it too long which is making it worse -
I have a series of open support tickets which are supposed to be updated on a daily basis, the problem is that they aren't always being updated daily. So, the business wants to know the number of days from when a ticket was last updated and today's
date. I have this basic calculation and it's working fine, however now the business wants to exclude weekends from the calculation. The other problem is that some reps DO go in on weekends and update their tickets, so sometimes there will be updates
made on weekend dates.
To give an example -
Today's date is 2014-02-10 (Monday). A ticket was last updated last Thursday, 2014-01-30. The difference between the two dates is 11, so it's been 11 days since the ticket was last updated. Now, if I exclude Saturdays and Sundays, then
it's actually been 7 days since the ticket was last updated. I'm not sure how to do this in T-SQL.
Now, to further complicate the problem, sometimes a ticket IS updated on a Saturday or Sunday. So, if a ticket was updated on 2014-02-02 (Sunday), then it should be counted. Again i'm not sure how to do this.
What gets me is that this is probably fairly simple and i've just been staring at it too long. In the meantime, can someone offer some guidance?
Thanks!!I've adapted this from a function on my blog. you will need to add set the YourTicketTable to where ever your tickets are stored.
CREATE
FUNCTION [dbo].[CalcWorkDaysBetween](@StartDate
As DateTime,@EndDate
AS DateTime)
RETURNS
INT AS
BEGIN
SET @EndDate
=DATEADD(DAY,1,@EndDate)
DECLARE @Count
AS Int= 0
DECLARE @Date
As Date=@StartDate
WHILE @Date
< @EndDate
BEGIN
IF (DATEPART(WEEKDAY,@Date)IN(1,7)
OR (SELECT
Count(*)
FROM YourTicketTable WHERE TicketDate=@Date)=1)
BEGIN
SELECT @Count = @Count
+ 1
END
SELECT @Date=DATEADD(Day,
1,@Date)
END
RETURN
DATEDIFF(DAY,@StartDate,@EndDate)- @Count
END
Regards, -
How to calculate number of days in hijri
Dear all,
I need to develop a custom report in which i required to calculate number of days in hijri month and also the first and last day of the hijri month. we normally use Last_date(sysdate) function to get the last date of the english calender. but how can we find same for month.
Looking after for your support.
Regards,
SaquibConvert to hirjih date using:
select
to_char(sysdate,'YYYY/MM/DD','NLS_CALENDAR=''English Hijrah''') hijrih_date
from dual;
You can replace sysdate with the date of your choice.
Also I wrote this for my last project:
/* get hirjih date */
FUNCTION get_hijrah_date(
p_date in date,
p_date_format in varchar2
) return varchar2
is
v_hijrah_date varchar2(500);
begin
select
to_char(p_date,p_date_format,'NLS_CALENDAR=''English Hijrah''')
into v_hijrah_date
from dual;
return v_hijrah_date;
end get_hijrah_date;
So you can have get_hijrah_date(sysdate,'DD-MON-YYYY') from dual;
(or any other date formate of your choice)
Edited by: igwe on Jan 30, 2013 8:07 AM -
Calculate number of days between two festival dates in payroll schema
Hi Experts,
According to my company policy:
If an empl termination happens before Eid festival of the current year, then the pro-rated Eid bonus (yearly) is based on:
(The duration between Eid Festival date of previous year - Eid festival date of current year.)/350 days
Time Evaluation is not implemented in the system. Only payroll is implemented.
My question: How can I capture the number of days between (Eid Festival date of previous year - Eid festival date of current year) in the payroll schema ?
Regards,
Somdeb.Hi,
You can try using date specification. If you update last year eed holiday date for the employee then you can use the operand F along with NUM to get days between last eed holiday and current payroll period last day.
i.e NUM=FaaT 0
F is operand to query date specification.
aa is the date specification.
T is for unit and it gives number of days
next space is for current payroll period last day and 0 will reset alternate date to zero if no date specification is mentioned.
Basically this will give number of days from date mentioned in date type aa to current period last day. For more info you can go through documentation on operand F for NUM.
Let us know if this helps.
Regards,
Poorvi. -
How to Calculate number of months between two dates
Hi All,
In one of the fomr developments, I have to calculate the
Number of Days
Number of Months ( Considering Leap Year) provided by the dates, end user enters in the form,
After going thorugh some forum discussion, I have come to know about so many things which were not clear till now.
I have gone through various forums too, some one suggets to make use of FORM CALC and some other JAVA SCRIPT. But the logic i want to build in java script.
The most interesting point is the DATE object is not getting created when i write the below code
var startDate = new DATE(oYear, oMonth, oDay);
I am still not clear, that really the date object gets created in Adobe form If so the why the alert box is getting populated when i write below lines
var oTemp = startDate.getFullYear();
xfa.host.messagebox(oTemp);
So, there are so many unclear things,
If any one can help me by suggesting the approach and how to build the logic in the JavaScript I would be really thankful
Regards
PavanChandHi,
ChakravarthyDBA wrote:
Hi
I want number of Sundays between two dates
example
number of Sundays count between '01-04-2013' and '30-04-2013' in one select query I have to include this as sub query in my select statement.Here's one way:
SELECT early_date
, late_date
, ( TRUNC (late_date + 1, 'IW')
- TRUNC (early_date, 'IW')
) / 7 AS sundays
FROM table_x
;This does not depend on your NLS settings.
I hope this answers your question.
If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only), and also post the results you want from that data.
Point out where the statment above is getting the wrong results, and explain, using specific examples, how you get the right results from the given data in those places.
Always say which version of Oracle you're using (e.g., 11.2.0.2.0).
See the forum FAQ {message:id=9360002} -
How to calculate Number of Hours between 2 dates
Hi,
I have a Column in a table of datatype DATE i.e. Update_Date. Now How do I calculate number of hours passed starting from this date entered in the Update_Date column to SYSDATE. e.g. if the date in column is 2-FEB-2009 and the sysdate is 2/2/2009 2:07:40 AM it should give me 24. How can I get this number of hours.
Update_Date - Sysdate = Number of Hours.
ThanksWhen you subtract two dates in Oracle, you get a difference in terms of days. Just multiply that by 24 to get hours.
SELECT (sysdate - update_date) days,
(sysdate - update_date) * 24 hours
FROM your_tableThat said, it is not obvious how your example works. You state
if the date in column is 2-FEB-2009 and the sysdate is 2/2/2009 2:07:40 AM it should give me 24Since both dates are on February 2, 2009, the only difference is in the time component. If we assume that the time component of the UPDATE_DATE value is midnight since it is not specified, there is a little more than 2 hours of difference between the two dates. How is it that you determine there are 24 hours of difference?
Justin
Edited by: Justin Cave on Feb 2, 2009 10:39 AM -
How to calculate number of days in ABAP?
Hi,
I have a condition as below:
If (field1 - field2) > 12 Months
E.g field1 = 31.05.2011 & field2 = 10.11.2011
Can SAP actually minus dates and check if the difference is greater than 12 months?
How do I perform this calculation?
Pls advice.
Thanks!
Moderator message : Date FAQ, duplicate post. Thread locked.
Edited by: Vinod Kumar on Mar 2, 2012 1:50 PMHi,
If your calculating dates please do not manually calculate it like that.
You need to determine like week numbers, month and days.
The best way to do it is by using FM related to dates. Play around with these FMs in your program:
Function Modules related to Date and Time Calculations
CALCULATE_DATE - Calculates the future date based on the input .
DATE_TO_DAY - Returns the Day for the entered date.
DATE_COMPUTE_DAY - Returns weekday for a date
DATE_GET_WEEK - Returns week for a date
RP_CALC_DATE_IN_INTERVAL - Add days / months to a date
DAY_ATTRIBUTES_GET - Returns attributes for a range of dates specified
MONTHS_BETWEEN_TWO_DATES - To get the number of months between the two dates.
END_OF_MONTH_DETERMINE_2 - Determines the End of a Month.
HR_HK_DIFF_BT_2_DATES -Find the difference between two dates in years, months and days.
FIMA_DAYS_AND_MONTHS_AND_YEARS - Find the difference between two dates in years, months and days.
WEEK_GET_FIRST_DAY - Get the first day of the week
SD_CALC_DURATION_FROM_DATETIME - Find the difference between two date/time and report the difference in hours
L_MC_TIME_DIFFERENCE - Find the time difference between two date/time
HR_99S_INTERVAL_BETWEEN_DATES - Difference between two dates in days, weeks, months
LAST_DAY_OF_MONTHS - Returns the last day of the month
DATE_CHECK_PLAUSIBILITY - Check for the invalid date.
DATE_2D_TO_4D_CONVERSION - Year entry: 2-character to 4-character.
DAY_IN_WEEK - Input date and will give the name of the day 1-monday,2-Tuesday....
SD_DATETIME_DIFFERENCE - Give the difference in Days and Time for 2 dates -
How to calculate number of days from a date field
Dear BW Experts.
I have a field 'Create Date' in the BEx query. Now we need to create a variable which should give the number of days from the date of running the query (sy-datum) to the Create Date.
This will help the users to get records which are say, 30 days old (Sy-datum - create date = 30) or 10 days old etc.
Could you suggest as to how to create this variable.
Thanks,
SaiHi,
Step 1: Create variable on "Create Date" with User entry processing type
Step 2: Create a restricted KF for Sales & restrict it on "Create Date" to get "Sales on day"
Step 3: Manipulate the values of "Create Date" on which you could restrict "Sales" again and again to get other values
Step 4: Create one variable (ZPUTMNTH) for u201CMonth to Dateu201D with processing by u201CCustomer Exitu201D. This variable was created on u201CDateu201D characteristics.
Step 5 : Goto C-mod t-code and use EXIT_SAPLRRS0_001
to calculate "month to date" user input is "Calday" Key Date
WHEN 'ZPUTMNTH'.
IF I_STEP = 2. "after the popup
LOOP AT I_T_VAR_RANGE INTO LOC_VAR_RANGE
WHERE VNAM = 'ZPDATE'.
CLEAR L_S_RANGE.
L_S_RANGE-LOW = LOC_VAR_RANGE-LOW(6). "low value, e.g.YYYYMM (200606) part of key date (20060625)
L_S_RANGE-LOW+6(2) = '01'. u201C low value e..g. YYYYMM01 (20060601)
L_S_RANGE-HIGH = LOC_VAR_RANGE-LOW. "high value = input
L_S_RANGE-SIGN = 'I'.
L_S_RANGE-OPT = 'BT'.
APPEND L_S_RANGE TO E_T_RANGE.
EXIT.
ENDLOOP.
ENDIF.
Assign if helps.....
Regards,
Suman -
Formula to calculate number of days between today's date & given date BEx
Hello,
I have a date available as an attribute of dimension characteristic. How do I get current date (sy-datum) to calculate the # of days (or difference) between query execution date and given date.
Is there a system field to get current or today's date .
I am thinking to have this as calculated KF in BEx.
Any suggestions or tips
ThanksHi,
Create a variable on the attribute(date attribute) of characterstic. Use this variable to create a formula variable , in which you fin out the difference between current date and varaible.
There is a good document on using the attributes in the calculation in service.sap.com/bi
In infoindex--> calculation with attributes.
With rgds,
Anil Kumar Sharma .P -
How to calculate number of days excluding weekends
I have the following <u>key figures</u> in my InfoCube:
Date Released to Vendors key figure - ZRELDT
Date Awarded to a Vendor key figure - ZAWRDT
In my BEx query, I need to calculate the difference between these two key figures but the weekends should be excluded. For example, if the value of ZRELDT is 08/10/2007 (which is a Friday) and the value of ZAWRDT is 08/13/2007, the result should just be 1 day and not 3 days since the other days pertain to a Saturday and a Sunday.
How do I address this in the formula when creating the Query?
thanks.Hi,
Use func module HOLIDAY_GET need to pass the Holiday Cal the company use
and also
FM: DATE_CONVERT_TO_FACTORYDATE.
One way to use this:
Assuming:
- You have the start & end dates in variables.
- Keep a few counters
Logic:
- Pass start date to DATE_CONVERT_TO_FACTORY_DATE with the parameter +
- If this date is not a factory date, the next date which is a factory day is returned. (I.e. passed Sunday as param, got a Monday date returned). If the day passed to the function is the same as the date returned, this is a factory day (working day)
- If the date passed to the function is not the same as the returned day then this day was not a factory day, meaning not a work date. Add 1 to a counter
- Pass the first day + 1 (use another counter for + N)
- Stop loop when passed parameter is equal to stop date.
You can replicate the factory calendar from R/3, CRM etc in your source system in RSA1 (transfer globals). In your function call, you specify which factory calendar to use
hope this help -
How to calculate number of sundays and saturdays between two Dates
friends i want to calculate how many Sundays come in two Dates
i have tried following code which is hard coded i have to impliment method which can give me number of Sundays between two Dates
please help me
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar ;
import java.util.GregorianCalendar;
public class DateDiffCalculator {
private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MMM-dd");
public DateDiffCalculator() {
public static Date getDate (String date) throws Exception {
//log.debug(" "+date);
return SDF.parse(date);
public static Date getDate (Date date) throws Exception {
// log.debug("date is "+date);
return getDate(SDF.format(date));
public static long getDiffInDays(Date d1,Date d2) {
boolean isdiffGreaterThanYear=false;
long diffInMilliSeconds=d1.getTime()-d2.getTime();
return diffInMilliSeconds/(1000*60*60*24);
public static int getYear(String date) {
//String[] day= {Sun,Mon,Tue,Wed,Thu,Fri,Sat};
Integer year=new Integer(date.substring(0,4));
return year.intValue();
public static int getMonth(String date) {
//String date.substring(5,7);
System.out.println(" "+date.substring(5,8));
String m= date.substring(5,8);
int month=0;
if(m.equalsIgnoreCase("Jan")) {
month=1;
if(m.equalsIgnoreCase("Feb")) {
month=2;
if(m.equalsIgnoreCase("Mar")) {
month=3;
if(m.equalsIgnoreCase("Apr")) {
month=4;
if(m.equalsIgnoreCase("May")) {
month=5;
if(m.equalsIgnoreCase("Jun")) {
month=6;
if(m.equalsIgnoreCase("Jul")) {
month=7;
if(m.equalsIgnoreCase("Aug")) {
month=8;
if(m.equalsIgnoreCase("Sep")) {
month=9;
if(m.equalsIgnoreCase("Oct")) {
month=10;
if(m.equalsIgnoreCase("Nov")) {
month=11;
if(m.equalsIgnoreCase("Dec")) {
month=12;
return month;
public static int getDay(String date) {
Integer day=new Integer(date.substring(9,11));
return day.intValue();
public static int getNumberofSundays(String d1,String d2) throws Exception {
//d1 is leave start date d2 is leave end date
// get object in Date form
Date date1=getDate(d1);
Date date2=getDate(d2);
// now get calender objects from it
GregorianCalendar c1= new GregorianCalendar(getYear(d1),getMonth(d1),getDay(d1));
GregorianCalendar c2= new GregorianCalendar(getYear(d2),getMonth(d2),getDay(d2));
// get period
long leavePeriod = getDiffInDays(date1,date2);
return 12; // it should return number of sundays but we type 12 to perform compilation
public static void main(String[] arg)throws Exception {
System.out.println(" "+getNumberofSundays("2005-Oct-07","2006-Mar-01"));
}thanks now i have modified the get Month Code
as follows
public static int getMonth(String date) {
//String date.substring(5,7);
System.out.println(" "+date.substring(5,8));
String m= date.substring(5,8);
int month=0;
if(m.equalsIgnoreCase("Jan")) {
month=0;
if(m.equalsIgnoreCase("Feb")) {
month=1;
if(m.equalsIgnoreCase("Mar")) {
month=2;
if(m.equalsIgnoreCase("Apr")) {
month=3;
if(m.equalsIgnoreCase("May")) {
month=4;
if(m.equalsIgnoreCase("Jun")) {
month=5;
if(m.equalsIgnoreCase("Jul")) {
month=6;
if(m.equalsIgnoreCase("Aug")) {
month=7;
if(m.equalsIgnoreCase("Sep")) {
month=8;
if(m.equalsIgnoreCase("Oct")) {
month=9;
if(m.equalsIgnoreCase("Nov")) {
month=10;
if(m.equalsIgnoreCase("Dec")) {
month=11;
return month;
but question remains same how to calculate number of Sundays Between 2 Dates -
Number of days between to dates
Hello to all,
I would like to define a formula to calculate number of days between two dates and update the value in a key figure.
*operand: {Name of keyfigure,Fecha ini (Mes/Año),Fecha Fin (Mes/Año)}
DATA FECHAINI TYPE ZIOV_FEIN.
DATA FECHAFIN TYPE ZIOV_FFIM.
DATA INI TYPE 0CALMONTH.
DATA FIN TYPE 0CALMONTH.
DATA DIA_INI TYPE D.
DATA DIA_FIN TYPE D.
DATA DIAS TYPE F.
FOREACH FECHAINI, FECHAFIN.
INI = FECHAINI.
FIN = FECHAFIN.
*C2DATE Determine end period date
DIA_INI = C2DATE(INI, E).
DIA_FIN = C2DATE(FIN, E).
DIAS = DIA_FIN - DIA_INI.
{ZIOV_DIAS,FECHAINI,FECHAFIN} = DIAS.
ENDFOR.
Problem: UPF057 type F conflicts with type D.
Help would be much appreciated.
Regards,
PatríciaThe function is built in:
CALL METHOD CL_RSAR_FUNCTION=>DATE_DIFF(
EXPORTING I_DATE_1 = L_ARG2
I_DATE_2 = L_ARG3
IMPORTING E_RESULT = L_ARG1 ) -
I wanted to know how do you calculate the number of days between two dates
i wanted to know how do you calculate the number of days between two dates in java ? i get both the dates from the database. i guess there are many issues like leap year and Febuary having diff no of months ..etc.
thanks..
I solve my problem as
public class MyExample {
public static void main(String a[]) {
String stdate = "2009-03-01";
java.sql.Date currentDate = new java.sql.Date(System.currentTimeMillis());
java.sql.Date preDate = java.sql.Date.valueOf(stdate);
System.out.println(currentDate);
System.out.println(preDate);
// int dateCom = preDate.compareTo(currentDate);
// System.out.println(dateCom);
long diff = currentDate.getTime() - preDate.getTime();
int days = (int) Math.floor(diff / (24 * 60 * 60 * 1000));
System.out.println(days);
}
Maybe you are looking for
-
Using more than one i-Tunes library
Ahem - apologies if this is a bit of a thicko question - but does anyone know if it's possible to use two i-Tunes libraries i.e. I have one on my MAC at home and a totally different one on my PC at work - but when I plug my Shuffle in to either one t
-
PSC 1510 always prints test page on startup; settings menu no help
Hi, My HP PSC 1510 All-in-one printer always prints a test page when I start it up, wasting ink and paper. I tried two things, neither of which solved the problem: - Checking the settings, services, and every other menu I could find for any related o
-
I was told a bunch of things from a bunch of places.. Story 1: source: some ad I read) Call-id on TV needs either digital voice or a regular fios pots phone + fios internet. I have the latter & the feature does show up on the box but when I try to e
-
Change default language on browser thru WD Java
hi all, I already created .xlf for internationalization. The scenario is to display the page on the language regard to user's nationality. Do I have to create the BAPI to send the nationality of SAP user to let the WD Java knows the user's nationalit
-
Upgraded my N8-00 to Belle a few days ago and I have had all kinds of problems. How can I "downgrade" the phone to Anna?