Get Actual Difference in Months DateTime ASP.NET MVC - asp.net-mvc

I have this dates here:
date1 = 2015-1-1
date2 = 2014-1-1
When I use this code:
int difference = date1.Value.Month - date2.Value.Month
This returns 0. I want the actual result to be 12 months since the date difference is within a year.
Someone help out? Completely new to this.

Try this code
DateTime date1 = Convert.ToDateTime("2015-1-1");
DateTime date2 = Convert.ToDateTime("2014-1-1");
Console.WriteLine((date1.Month - date2.Month) + 12 * (date1.Year - date2.Year));

var difference = date1.Value.Ticks - date2.Value.Ticks;
var dateDifference = new DateTime(difference);
int numberOfMonths = (dateDifference.Years * 12) + dateDifference.Months;

You can't get the exact result since day/years can change but you still
can try this:
//you can determine that the average month has 30.44 days (source:google)
const double daysToMonths = 30.4368499;
DateTime date1 = Convert.ToDateTime("2015-1-1");
DateTime date2 = Convert.ToDateTime("2014-1-1");
//round is optional here
Double Diff = Math.Round(date1.Subtract(date2).TotalDays/daysToMonths,0);

I resolved this issue by adding Microsoft.VisualBasic in my reference and by using the DateDiff function from Visual Basic. By using this, I don't need to manually compute the date anymore, I just set the interval and the 2 dates then it executes perfectly.
DateAndTime.DateDiff(DateInterval.Month, (DateTime)promoevent.TargetStartDate, (DateTime)promoevent.TargetEndDate);

Related

How to calculate the difference between two dates with moment that works in iOS

I use momentJS for date conversion but recently ran into a problem that appears only on iOS when calculating the difference between 2 dates.
I have two strings that looks like this:
const startDate = "08-21-2022 10:28 AM";
const endDate = "08-31-2022 10:28 AM";
In a non iOS system this works:
moment(endDate).diff(moment(startDate), "days")
But on iOS it returns NaN with a warning:
Deprecation warning: value provided is not in a recognized RFC2822 or
ISO format. moment construction falls back to js Date(), which is not
reliable across all browsers and versions. Non RFC2822/ISO date
formats are discouraged and will be removed in an upcoming major
release. Please refer to
http://momentjs.com/guides/#/warnings/js-date/ for more info.
...
I tried the following but without success:
var test1 = moment(dateString);
var test2 = moment(dateString2);
console.log(test2.diff(test1, "days"));
var test5 = moment(dateString).toISOString();
var test6 = moment(dateString2).toISOString();
console.log(moment(test6).diff(moment(test5), "days"));
console.log(moment(dateString).valueOf());
They all seem to return NaN. What can I do to calculate the difference? Even console.log(new Date())
What seems to work is this:
var test3 = moment([2007, 0, 29]);
var test4 = moment([2007, 0, 28]);
test4.diff(test3, "days");
But I'm unsure how I could safely extract the year, I tried these:
var test7 = moment(dateString).year();
console.log("5", test7);
var test8 = moment(dateString).toISOString();
console.log("6", moment(test8).year());
But they all returned NaN;
I have a codesandbox to test on iPhone https://codesandbox.io/s/lively-framework-622p7r?file=/src/App.js

Convert hh:mm:ss:mm to hh:mm:ss

I have written a code that subtracts 2 DateTime properties and gives AHT for that task. AHT shows as follows 00:00:00:567, but how can display this as hh:mm:ss format.
Kindly help with this, help is very much appreciated
Below is my Action created.
using(Db db = new Db())
{
Chat newDTO = db.Chats.Where(x => x.ChatId == id).FirstOrDefault();
DateTime startTime = Convert.ToDateTime(newDTO.FeedbackDateTime);
DateTime endtime = Convert.ToDateTime(newDTO.FeedbackSharedDateTime);
TimeSpan duration = endtime.Subtract(startTime);
//hh:mm:ss
string stringAHT = string.Format("{0:D2}:{1:D2}:{2:D2}:{3:D2}",
24 * duration.Days + duration.Hours,
duration.Minutes,
duration.Seconds,
duration.Milliseconds
);
newDTO.AuditorAHT = stringAHT;
db.SaveChanges();
}
Thank you in advance.
Finally made it work
Created AuditorAht field as string data type
In Controller:
string aht = string.Format("0:hh\\:mm\\:ss", dto.datetime1 - dto.datetime2);
dto.AuditorAht = aht;
db.Savechanges();
Now Average Time is storing as hh:mm:ss format as I wanted it to.

Flutter Timezone (as ZoneId)

I am relative new to Flutter. While I was experimenting, I came across with an issue. My REST Api takes a timezone parameter (Zone ID format such as Europe/London).
I saw both https://pub.dartlang.org/packages/flutter_native_timezone and https://pub.dartlang.org/packages/timezone, but neither of those serve my needs.
My goal is, when the user connect to the internet (without giving any location access to the app, if it is possible), get the timezone in ZoneId format and feed my back end in order to make the necessary date and time adjustments. Something similar to this
>>> var timezone = jstz.determine();
>>> timezone.name();
"Europe/London"
Presented in https://bitbucket.org/pellepim/jstimezonedetect
Any insights will be really helpful.
Thanks in advance
I've been also looking for this and here's what I found: https://pub.dev/packages/flutter_native_timezone
It a bit hacky under the hood, but it seems to work properly on both iOS and Android. Hope this will help someone in need.
Usage:
final String currentTimeZone = await FlutterNativeTimezone.getLocalTimezone();
print(currentTimeZone); // Europe/Moscow
Came up with a simple solution:
//server time(UTC)
String date_to_parse = "2019-06-23 12:59:43.444896+00:00";
DateTime server_datetime = DateTime.parse(date_to_parse);
//get current system local time
DateTime local_datetime = DateTime.now();
//get time diff
var timezoneOffset = local_datetime.timeZoneOffset;
var time_diff = new Duration(hours: timezoneOffset.inHours, minutes: timezoneOffset.inMinutes % 60);
//adjust the time diff
var new_local_time = server_datetime.add(time_diff);
After doing some digging, I found a (temporary) workaround to my issue.
Using
var now = new DateTime.now();
var timezoneOffset = now.timeZoneOffset;
I got the timezoneOffset in UTC format in flutter. Then send it to my back end as string (i.e. "-04") and drift my ZoneId properly.
Integer tzOffsetHour = Integer.valueOf(covertToTimezone);
ZoneOffset offset = ZoneOffset.ofHoursMinutes(tzOffsetHour, 0);
ZoneId zoneTZ = ZoneId.ofOffset("UTC", offset);
LocalDateTime localDateTimeClient = new Date().toInstant().atZone(zoneTZ).toLocalDateTime();
As a result I take the local time and date as stated in user's device, without using any location services, which was my goal from the beginning.
Until now, I have not faced any issues... we will see...
You can simply add .toLocal() to your DateTime object.
myDate = otherDate.toLocal();
myDate = DateTime.parse(json['server_date']).toLocal();
If you are just after the Time Zone offset. All you need is one line of code
int tzOffset = DateTime.now().timeZoneOffset.inHours;
The best way is to use timezone. as below
import 'package:timezone/data/latest.dart' as tz;
import 'package:timezone/timezone.dart' as tz;
String getNameLocalTimeZone() {
tz.initializeTimeZones();
var locations = tz.timeZoneDatabase.locations;
int milliseconds=DateTime.now().timeZoneOffset.inMilliseconds;
String name = "";
locations.forEach((key, value) {
for (var element in value.zones) {
if (element.offset == milliseconds) {
name = value.name;
break;
}
}
});
return name;
}
DateTime.now().timeZoneOffset // +5:30:00.000000 is expected format

Find Index of Array by NSDate?

I would like to find out the index of an array by an NSDate.
Ill tried:
var sectionsInTable = [NSDate]()
let indexOfElement = sectionsInTable.indexOf(date) // where date is an NSDate in my sectionsInTable Array
print(indexOfElement)
But ill always get false
How is it possible to get the index of an NSDate from an array?
Thanks in advance.
If you have exact copies of NSDate objects, your code should work:
let date = NSDate()
let date2 = date.copy() as! NSDate
var sectionsInTable: [NSDate] = [date]
let indexOfElement = sectionsInTable.indexOf(date2)
print(indexOfElement)
//prints: Optional(0)
Your approach should work fine. This code produces an index of 2:
let s = 31536000.0 // Seconds per Year
var tbl = [NSDate]()
tbl.append(NSDate(timeIntervalSince1970: 40*s)) // 0
tbl.append(NSDate(timeIntervalSince1970: 41*s)) // 1
tbl.append(NSDate(timeIntervalSince1970: 42*s)) // 2
tbl.append(NSDate(timeIntervalSince1970: 43*s)) // 3
let date = NSDate(timeIntervalSince1970: 42*s)
let indexOfElement = tbl.indexOf(date)
The most likely reason that you are not getting the proper index is that your search NSDate has a time component that does not match the time component in NSDate objects in the array. You can confirm that this is the case by printing both objects, and verifying their time component.
Since comparison depends on how deep you want to go with date time thing. I think you should just loop through your date array and compare if it's equal and return that index.

KendoUI 2013.3.1324: timezoneoffset and negative milliseconds value

I have updated my project to version 2013.3.1324 from 2013.3.1119 (with ASP.NET MVC wrappers)
And I saw the following after update:
DateTime is passed to the client as
"/Date(-498283200000)/"
if less than 1970 year and
"/Date(498283200000)/"
if more that 1970 year
I have found a strange code in the kendo.all.js file
dateRegExp = /^\/Date\((.*?)\)\/$/,
tzOffsetRegExp = /[+-]{1}\d+/,
...
if (value && value.indexOf("/D") === 0) {
date = dateRegExp.exec(value);
if (date) {
date = date[1];
tzoffset = tzOffsetRegExp.exec(date);
date = parseInt(date, 10);
if (tzoffset) {
date -= (parseInt(tzoffset[0], 10) * kendo.date.MS_PER_MINUTE);
}
return new Date(date);
}
}
Debug info:
Initial value:
Parsed date value:
Parsed tzo value:
And finally, result date value:
Actually I don't need time, only Date. Model property type is regular DateTime.
Also I can't find any issues with this release on the Kendo site.
What I'm doing wrong and what I need to do? (changing Kendo source is not an option I think...)
Example:
Live demo: http://jsbin.com/vebed/2/edit?html,js,output
The following:
alert(kendo.parseDate("/Date(-498283200000)/"))
shows
Thu Mar 18 1954 22:00:00 GMT+0200 (FLE Standard Time)
with the latest official version of Kendo UI.
Make sure you are not using an older version.
Here is a live demo: http://jsbin.com/vebed/1/edit
Issue was fixed in the Internal build 2013.3.1408
New code is:
if (value && value.indexOf("/D") === 0) {
date = dateRegExp.exec(value);
if (date) {
tzoffset = date = date[1];
date = parseInt(date, 10);
tzoffset = tzoffset.substring(1).split(signRegExp)[1];
if (tzoffset) {
date -= (parseInt(tzoffset, 10) * kendo.date.MS_PER_MINUTE);
}
return new Date(date);
}
}

Resources