Get Number of Months passed in Ruby - ruby

Is there an easy way to get the number of months(over multiple years) that have passed between two dates in ruby?

I found this solution, it seems logical and seems to work.
startdate = Time.local(2001,2,28,0,0)
enddate = Time.local(2003,3,30,0,0)
months = (enddate.month - startdate.month) + 12 * (enddate.year - startdate.year)
Reference: http://blog.mindtonic.net/calculating-the-number-of-months-between-two-dates-in-ruby/

You could provide some test cases, here's one try, not tested very much really:
def months_between d1, d2
d1, d2 = d2, d1 if d1 > d2
(d2.year - d1.year)*12 + d2.month - d1.month - (d2.day >= d1.day ? 0 : 1)
end

This addresses the month edge cases.(i.e. Mar 15 2009 - Jan 12 2010)
def months_between( d1, d2)
d1, d2 = d2, d1 if d1 > d2
y, m, d = (d2.year - d1.year), (d2.month - d1.month), (d2.day - d1.day)
m=m-1 if d < 0
y, m = (y-1), (m+12) if m < 0
y*12 + m
end

Related

How to add, subtract two or more DTPicker value in VB6

here is my GUI
Dim d1, d2, d3 As Date
Dim d4 As Integer
Dim x As Long
Option Explicit
Private Sub Command1_Click()
d1 = TimePicker.Value + DTPicker1.Value
d2 = TimePicker2.Value + DTPicker3.Value
x = DateDiff("h", d1, d2)
MsgBox x
End Sub
Private Sub Form_Load()
TimePicker.Format = dtpTime
TimePicker2.Format = dtpTime
End Sub
============================================
i want to calculate more number of hours in three or more days, I can only add two days it gaves me a value of 16hours and its correct, if i add more day it will add 24hours so it become 40 how can i fix this.I want to get 8hrs per day
If you use x = DateDiff("h", d1, d2), you will get the number of hours between d1 and d2.
If you use x = DateDiff("d", d1, d2), you will get the number of days between d1 and d2.
If you want to get 8 hours for each day, just multiply the DateDiff value by 8:
x = DateDiff("d", d1, d2) * 8

Classic ASP number of weekdays between dates

Is there any way in Classic ASP VBScript to get the number of weekdays between 2 dates? Obviously, we have the DateDiff() function but this will pull back the total number of days but I would like to omit the weekends.
You're right, DateDiff() doesn't cover this but it can be used in conjunction with WeekDay() to work out if a Day falls on a weekend.
By using DateDiff() to get the number of days we can then use a For loop to step through the days using DateAdd() to increment the day as we go and check whether the incremented date value is a particular WeekDay(). We can then decide based on this outcome whether to increment a counter that is storing our resulting number of weekdays.
Below is an example of how you would do this, the main logic has been encapsulated in a Function that you could include in a #include script file to use in multiple pages.
<%
Function DateDiffWeekDays(d1, d2)
Dim dy: dy = 0
Dim dys: dys = DateDiff("d", d1, d2)
Dim isWeekDay: isWeekDay = False
Dim wkd
Dim wd: wd = 0
For dy = 0 To dys
wkd = Weekday(DateAdd("d", dy, d1))
isWeekDay = Not (wkd = vbSunday Or wkd = vbSaturday)
If isWeekDay Then wd = wd + 1
Next
DateDiffWeekDays = wd
End Function
'Example of how to call the function and output to the page
Call Response.Write(DateDiffWeekDays(Date(), CDate("12 Nov 2018")))
%>
Output:
16
This is just a quick example and doesn't cover every possible usage case, the idea is it gives you a starting point that you can work from and improve.
VBScript does not include the requested operation, but as DateDiff with a ww interval returns the number of Sundays between two dates, ensuring that start and end dates are out of the weekend we can directly calculate the number of working days:
Option Explicit
Function WorkingDaysBetween( ByVal d1, ByVal d2 )
Dim d
' Adjust date order to simplify calcs and always return 0 or positive number
If d1 > d2 Then
d = d1 : d1 = d2 : d2 = d
End If
' Move start date forward if it is a weekend
d = WeekDay( d1, vbMonday )
If d > 5 Then d1 = DateAdd( "d", 3-(d\6 + d\7), d1)
' Move end date backward if it is a weekend
d = WeekDay( d2, vbMonday )
If d > 5 Then d2 = DateAdd( "d", -1*(d\6 + d\7), d2)
' Calculate
' DateDiff("d") = Number of days between dates
' +1 to include start day
' -2 * DateDiff("ww") to exclude weekends between dates
WorkingDaysBetween = 1 + DateDiff("d", d1, d2, vbMonday) - 2*DateDiff("ww", d1, d2, vbMonday)
' If the result is negative, there are no working days between both dates
If WorkingDaysBetween < 0 Then WorkingDaysBetween = 0
End Function

How to compute the total sum of squared error in k-mean clustering matlab?

I am implementing the k-means algorithm for given 4-dimensional data with k=# of cluster and i am running about 5 times with different initial points.
How can i compute the total sum of squared error (SSE)after each run?
4 Dimention 1 to 4 and blow
x1 1 2 3 4
x2 5 6 7 8
x3 9 10 11 12
x4 13 14 15 16
x5 17 18 19 20
I will be more than happy if anyone can help me with this.
Thanks
The kmeans() function already gives everything that you want directly. It has the following syntax for 3 clusters:
[idx,CentreCoordinates,SEE] = kmeans(yourData,3);
where
idx is the label of each observation (values 1 to 3 in this case)
CentreCoordinates are the coordinates of the cluster centres (each row is one centre)
SEE is the summed within-cluster euclidian distance of every observation to its nearest cluster centre - the SEE.
Since you actually don't need the indexes, you can ignore the first output of the function with ~ (tilde):
[~,CentreCoordinates,SEE] = kmeans(yourData,3);
This code is with the inbuilt MATLAB function 'k-means'. You need to modify it with your own algorithm for k-means. It shows the calculation of cluster centoirds and sum of square errors (also called the distrotion).
clc; close all; clear all;
data = readtable('data.txt'); % Importing the data-set
d1 = table2array(data(:, 2)); % Data in first dimension
d2 = table2array(data(:, 3)); % Data in second dimension
d3 = table2array(data(:, 4)); % Data in third dimension
d4 = table2array(data(:, 5)); % Data in fourth dimension
X = [d1, d2, d3, d4]; % Combining the data into a matrix
k = 3; % Number of clusters
idx = kmeans(X, 3); % Alpplying the k-means using inbuilt funciton
%% Separating the data in different dimension
d1_1 = d1(idx == 1); % d1 for the data in cluster 1
d2_1 = d2(idx == 1); % d2 for the data in cluster 1
d3_1 = d3(idx == 1); % d3 for the data in cluster 1
d4_1 = d4(idx == 1); % d4 for the data in cluster 1
%==============================
d1_2 = d1(idx == 2); % d1 for the data in cluster 2
d2_2 = d2(idx == 2); % d2 for the data in cluster 2
d3_2 = d3(idx == 2); % d3 for the data in cluster 2
d4_2 = d4(idx == 2); % d4 for the data in cluster 2
%==============================
d1_3 = d1(idx == 3); % d1 for the data in cluster 3
d2_3 = d2(idx == 3); % d2 for the data in cluster 3
d3_3 = d3(idx == 3); % d3 for the data in cluster 3
d4_3 = d4(idx == 3); % d4 for the data in cluster 3
%% Finding the co-ordinates of the cluster centroids
c1_d1 = mean(d1_1); % d1 value of the centroid for cluster 1
c1_d2 = mean(d2_1); % d2 value of the centroid for cluster 1
c1_d3 = mean(d3_1); % d2 value of the centroid for cluster 1
c1_d4 = mean(d4_1); % d2 value of the centroid for cluster 1
%====================================
c2_d1 = mean(d1_2); % d1 value of the centroid for cluster 2
c2_d2 = mean(d2_2); % d2 value of the centroid for cluster 2
c2_d3 = mean(d3_2); % d2 value of the centroid for cluster 2
c2_d4 = mean(d4_2); % d2 value of the centroid for cluster 2
%====================================
c3_d1 = mean(d1_3); % d1 value of the centroid for cluster 3
c3_d2 = mean(d2_3); % d2 value of the centroid for cluster 3
c3_d3 = mean(d3_3); % d2 value of the centroid for cluster 3
c3_d4 = mean(d4_3); % d2 value of the centroid for cluster 3
%% Calculating the distortion
distortion = 0; % Initialization
for n1 = 1 : length(d1_1)
distortion = distortion + ( ( ( c1_d1 - d1_1(n1) ).^2 ) + ( ( c1_d2 - d2_1(n1) ).^2 ) + ...
( ( c1_d3 - d3_1(n1) ).^2 ) + ( ( c1_d4 - d4_1(n1) ).^2 ) );
end
for n2 = 1 : length(d1_2)
distortion = distortion + ( ( ( c2_d1 - d1_2(n2) ).^2 ) + ( ( c2_d2 - d2_2(n2) ).^2 ) + ...
( ( c2_d3 - d3_2(n2) ).^2 ) + ( ( c2_d4 - d4_2(n2) ).^2 ) );
end
for n3 = 1 : length(d1_3)
distortion = distortion + ( ( ( c3_d1 - d1_3(n3) ).^2 ) + ( ( c3_d2 - d2_3(n3) ).^2 ) + ...
( ( c3_d3 - d3_3(n3) ).^2 ) + ( ( c3_d4 - d4_3(n3) ).^2 ) );
end
fprintf('The unnormalized sum of square error is %f\n', distortion);
fprintf('The co-ordinate of the cluster 1 is \t d1 = %f, d2 = %f, d3 = %f, d4 = %f\n', c1_d1, c1_d2, c1_d3, c1_d4);
fprintf('The co-ordinate of the cluster 2 is \t d1 = %f, d2 = %f, d3 = %f, d4 = %f\n', c2_d1, c2_d2, c2_d3, c2_d4);
fprintf('The co-ordinate of the cluster 3 is \t d1 = %f, d2 = %f, d3 = %f, d4 = %f\n', c3_d1, c3_d2, c3_d3, c3_d4);

date difference between two dates and the output should be in date format using vb script

I am new to VB Scripting. I have two dates, date_1 and date_2. I need to subtract date_1 from date_2 and the output the difference in date format.
example:
date_1 = 01-09-2014
date_2 = 08-10-2016
output would ideally be:
= date_2 - date_1
= 08-10-2016 - 01-09-2014
= 07-01-0002
Finally i need the output like 02 years, 01 months and 07 days.
Please help me out.
Many thanks in advance.
Take a look at the below code:
Dim date_1, date_2, l, r(2)
date_1 = "01-09-2014"
date_2 = "08-10-2016"
l = SetLocale(2057) ' UK
Delta 0, Array("yyyy", "m", "d"), Array("years", "months", "days"), r, CDate(date_1), CDate(date_2), False
SetLocale l
MsgBox Join(r, ", ") ' 2 years, 1 months, 7 days
Sub Delta(i, t, n, r, d1, d2, c)
Dim q, d
q = DateDiff(t(i), d1, d2)
If UBound(t) > i Then
Do
d = DateAdd(t(i), q, d1)
Delta i + 1, t, n, r, d, d2, c
If c Then Exit Do
q = q - 1
Loop
End If
c = q >= 0
r(i) = q & " " & n(i)
End Sub
You even can set the date and time and compute difference up to second:
Dim date_1, date_2, l, r(5)
date_1 = "01-09-2014 10:55:30"
date_2 = "08-10-2016 15:45:10"
l = SetLocale(2057) ' UK
Delta 0, Array("yyyy", "m", "d", "h", "n", "s"), Array("years", "months", "days", "hours", "minutes", "seconds"), r, CDate(date_1), CDate(date_2), False
SetLocale l
MsgBox Join(r, ", ") ' 2 years, 1 months, 7 days, 4 hours, 49 minutes, 40 seconds
Sub Delta(i, t, n, r, d1, d2, c)
Dim q, d
q = DateDiff(t(i), d1, d2)
If UBound(t) > i Then
Do
d = DateAdd(t(i), q, d1)
Delta i + 1, t, n, r, d, d2, c
If c Then Exit Do
q = q - 1
Loop
End If
c = q >= 0
r(i) = q & " " & n(i)
End Sub
Using some string functions , you can easily achieve your goal .
Hope this helps .
date_1 = InputBox("Enter first Date in format DD-MM-YYYY","Time Difference")
date_2 = InputBox("Enter second Date in format DD-MM-YYYY","Time Difference")
day_differ = Abs(CInt(Left(date_2 , 2)) - CInt(Left(date_1 , 2)))
month_differ = Abs(CInt(Mid(date_2 , 4 , 2)) - CInt(Mid(date_1 , 4 , 2)))
year_differ = Abs(CInt(Right(date_2 , 4)) - CInt(Right(date_1 , 4)))
wscript.echo "Date Difference is " & year_differ & " years, " & month_differ & " months and " & day_differ & " days."

UITextField int data type xcode

I am trying to get a mathmetical equation to recognise a + /- sign of an integer (either -1 or +1) entered in a UItextfield (s1, s2). So if the user enters different signs the equations will be subtracted from each other.
It seems that the sign is not being recognised for some reason and the program just adds d1 and d2.
-(IBAction)calculateD:(id)sender{
float n1, r1, n2, r1, d, d1, d2;
int s1, s2;
s1= [textfieldS1.text intvalue]; //etc for all variables
d1 = s1 * ((n1-1)/r1);
d2 = s2 * ((n2-1)/r2);
if (s1 != s2) { d = d1 - d2;}
else { d = d1 + d2;
}}
Any problems apparent in this code please?
I have no idea what you are trying to do here. Variables are not initialized and there is no specific reference to actual UITextField inside of the -calculateD: method. With this said, here are some hints, hope it will come in hand.
The signs s1, s2 are actually taken twice into a consideration. Once to produce d1, d2, and later to decide the (s1 != s2). Because of this, the latter will make sure you add two numbers of the same sign, possibly negating what you really want to obtain here. Example:
say that s1=+1, s1=+1, then you got d = ((n1-1)/r1) + ((n2-1)/r2);
say that s1=+1, s1=-1, then you got d = ((n1-1)/r1) + ((n2-1)/r2); the same as before;
Just drop the if, and leave a single: d = d1 + d2.

Resources