Calculating difference between time now and scheduledstart crm c# - dynamics-crm-2013

How can i calculate difference between the time now and the "scheduledstart" field (in appointment entity) and put the value into another number field ("el_early_cancel_notice" - like duration field).
This is what i wrote untill now but i don't know how to proceed. Can someone help?
if ((serviceAppontment.Attributes.Contains("scheduledstart")) && (serviceAppontment.Attributes["scheduledstart"] != null) && (TimeNow > SchelStart))
{
throw new InvalidPluginExecutionException(serviceAppontment.Attributes["scheduledstart"].ToString());
try
{
//here i need to calculate the difference and i don't know where to begin...
}

DateTime startDate = (DateTime)serviceAppontment["scheduledstart"];
TimeSpan diff = DateTime.UtcNow - startDate;
serviceAppointment["el_early_cancel_notice"] = diff.Days;
localContext.OrganizationService.Update(serviceAppoinment);
Because DateTime is stored in UTC format in CRM, you need to deal with DateTime in UTC. And I assume you want duration in days. More about TimeSpan here.
Good luck!

1) Cast your field to a date time:
DateTime startDate = (DateTime)serviceAppontment.Attributes["scheduledstart"];
2) Use one of these methods to get a TimeSpan.
3) Update your el_early_cancel_notice field with information from the TimeSpan:
serviceAppontment.Attributes["el_early_cancel_notice"] = [Appropriate number from TimeSpan];

Related

Compare Dates in Kotlin

How can i compare Dates in Kotlin?
I have the Date of an Event as a String (Format:dd/mm/yy) and I want to check if it is within the next 7 Days of the current Date.
The time in this case is not relevant or if needet I would use midnight.
Can someone please help me with this?
In my current code i got both Dates by this:
val date = document.data["Date"].toString() //Example: 22/08/22 (dd/MM/yy)
val today = SimpleDateFormat("dd/MM/yy").format(Date()).toString()
this is within a Android environment.
I can't get the date more specific because i am getting it from a Database.
Parse string into LocalDate using its parse method. There’s no out-of-the-box DateTimeFormatter for dd/mm/yy format, but you can trivially create one using DateTimeFormatter.ofPattern.
Get current date using LocalDate.now().
diff = ChronoUnit.DAYS.between(now, date1)

How to check for current date, if the column having date and time?

How should I match today's / current date irrespective of the time with column having date as (yyyy-mm-dd HH:mm:ss) eg (2019-04-05 16:00:00.0)
Using Grails GORM findBy method?
You could use between.
def today = new Date().clearTime()
def tomorrow = use( TimeCategory ){ today + 1.day }.clearTime()
YourDomain.findByYourDateBetween( today, tomorrow )
Probably more suitable for findAllBy.

Visual Studio: How to get the number days and hours from two DateTimePicker

I need your help, I can't figure out what to do.
I have two DateTimePicker:
DateTimePicker1 = which returns a date
DateTimePicker2 - which returns a time
I would like to get the difference from the current date & time to those two DateTimePicker's to get the number of days and hours.
I'm not exactly sure what you are trying to achieve. You can do the operations you describe as below though
static void Main(string[] args)
{
DateTime dpt1 = new DateTime(2019, 02, 15);
DateTime dpt2 = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 10, 30, 45);
DateTime combined = new DateTime(dpt1.Year, dpt1.Month, dpt1.Day, dpt2.Hour, dpt2.Minute, dpt2.Second);
var diff = new DateTime(DateTime.Now.Ticks - combined.Ticks);
var hours = diff.Hour;
}
I see an issue with what you are asking though. "I would like the difference from the current date & time to those two DateTimePicker's so I can get the total number of days and hours." Unfortunately you won't be able to extract the day differences since in the dpt2 you are only selected hours/minutes/seconds. The month/day/year field is essentially useless and unusable in the calculation.
If you want to specifically get the timespan difference you can easily do that with
TimeSpan.FromTicks(DateTime.Now.Ticks - combined.Ticks);
Dim combine As Date = DateTimePicker1.Value.Date + DateTimePicker2.Value.TimeOfDay
Dim currentDate As Date = Date.Now()
Dim timeDifference As TimeSpan = combine - currentDate

Error: Date Type Conversion from String in VB .Net

For the following code, I am receiving this error: "Conversion from String "10/22.2014 12:00:00 A10" to type 'Date' is not valid." Note - in comparison to the code, below - the error message's conversion of AM to A10.
What I Am Trying To Do
I am trying to give a user the ability to query a database for transactions that occurred, today. In order to do this, I need to specify the timestamp for the transaction, i.e. MM/dd/yyyy timestamp. I have consulted the MSDN documentation; however, am unable to get my code to function, properly.
By default, Date objects appear to drop their timestamp (this may be a result of the code I am working with, e.g. the casting); therefore, when specifying a date range of "today" (Today's Data - Today's Date), I am left with the default behaviour of the object: Today's Date 12:00:00 AM - Today's Date 12:00:00 AM. Regardless as to why this is happening, this is the problem with which I am left.
The objective: MM/dd/yyyy 12:00:00 AM - MM/dd/yy 11:59:59 PM (the day being the same).
My goal is to force a particular timestamp for a Date object (note this is not a DateTime object). By specifyiong the time range, I am able to grab all data from a database for today.
What I've Got
Below, is the code and, below that, the description (I've tried to condense the code as much as possible). You'll also note that this is only half of the code, i.e. the FromDate portion (presumably the format can be replicated for the ToDate:
Public Shared Function ToFromDate(ByVal aValue As Object) As Date
Dim Result As Date
Try
Result = CDate(aValue)
Catch ex As Exception
Result = Now
End Try
Result = CDate(String.Format("{0:MM/dd/yyyy 12:00:00 AM}", Result))
Return Result
End Function
The above code takes as an argument a DateTime, e.g. 10\10\2010 12:15:63 PM (and, for the purposes of my problem, the timestamp is included). Again, I am trying to take that Date with timestamp and change the time. Result receives aValue, casting the object as Date to "ensure" it is a date.
After Result receives a value (as when declaring a Date it is initialized to #12:00:00 AM#, interestingly enough), I attempt to CDate() a formatted String object. I have also attempted to remove the second cast, yet still receive the same error (the Result = CDate(String...) line throwing the error).
Question(s)
The main question: how do I appropriately cast a date to include a specified time?
The second, trivial question: what's with the # surrounding the Date? Is this a SQL 'thing'?
Here's my work around for the above not working, so far:
Dim Result As Date
Dim DateString As String = CStr(aValue)
Dim TestDateString As String = DateString.Substring(0, DateString.IndexOf("/"))
Dim NewDateString As String = ""
If TestDateString.Length = 2 Then
NewDateString = DateString.Substring(0, 10)
Else
NewDateString = DateString.Substring(0, 8)
End If
NewDateString = NewDateString + " 12:00:00 AM"
NewDateString = CObj("#" + NewDateString + "#")
Result = CDate(NewDateString)
Return Result
First, a date is the number of ticks since a point in time. Formatting it to a string and then converting to a date does nothing but spin the wheels of your CPU.
Because of culture issues, you should always create dates using NEW DATE(?,?,?,etc)
Second, the # is a vb6 way of creating dates (and MS Access) that is there for backwards compatibility.
Third, If you have a date (no time or as of midnight), and you want it to be as of say 6AM, you simply add the time you want. IE:
Dim d As Date = New Date(2014,1,1)
d = d.AddHours(6)
'Result: d = 1/1/2014 6:00:00 AM
Lastly, if you have a date and time and you want to remove the time, there are many ways but this is the one I like:
Dim d As Date = Now
d = New Date(d.Year, d.Month, d.Day)

exclude weekends from datetime

I need to exclude weekends from this line.
If Convert.ToDateTime(e.Row.Cells(4).Text).ToString < DateTime.Now.AddDays(-3) Then
e.Row.BackColor = System.Drawing.Color.FromName("red")
I hope there is an easy way to do this!
Use the following code
DateDiff(DateInterval.Weekday,Date2, Date1)
--Hiren V
I've had to do something similar once.
The trick is to take the strings from your rows, convert them to a DateTime like you have it, then check the DayOfWeek property of the DateTime object.
The DayOfWeek property can be used as such:
DateTime date = new DateTime();
label1.text = date.DayOfWeek.ToString();
With that, just check if the value is equal to a string of "Saturday" or "Sunday".
That should help you filter off your weekends.