I have a c# DateTime passed to the client as:
1980-01-20T00:00:00
How do i convert it to javascript DateTime? I tried doing
var date = new Date(1980-01-20T00:00:00) but this gives me an error
Put it in quotes:
var date = new Date("1980-01-20T00:00:00")
var date = new Date("1980-01-20T00:00:00")
alert(date)
What you need is the amount of miliseconds from 1970:
long epochTicks = new DateTime(1970, 1, 1).Ticks
long unixTime = ((DateTime.UtcNow.Ticks - epochTicks) / TimeSpan.TicksPerSecond);
long javascriptTyme=unixTime*1000;
Thats the value you want to send to javascript
Related
I am tring to save dates in my MongoDB table using C#.
Here is a JavaScript logic that send data using Ajax to C# controller
$(function ($, w, d) {
var _user = {}
//var time = moment("2016-04-02", "YYYYMMDD").fromNow()
//var bime = moment().endOf('day').fromNow();
//var crime = moment("20120620", "YYYYMMDD").fromNow();
// document.getElementById('time').innerHTML = time;
var obj = {};
var holidaylist = ["Mar-31-2018", "Apr-01-2018","Apr-04-2018","Apr-07-2018","Apr-08-2018"];
var startdate = new Date("Apr-02-2018");
obj.endDate = "Apr-06-2018";
obj.holidaylist = holidaylist;
obj.NumberOfCount = 9;
CallAjax("POST", '/LeaveManagement/', 'checkleavelogic', obj, onsuccessaddemployee, '');
here is the C# logic that saves the data in MongoDB:
public JsonResult checkLeaveLogic(LeaveLogicModel leaveLogic)
{
string strconnectiomstring = "mongodb://10.10.32.125:27017";
MongoClient Client = new MongoClient(strconnectiomstring);
var DB = Client.GetDatabase("TimeClock");
List<DateTime> leavesDate = new List<DateTime>();
var collection = DB.GetCollection<LeaveLogicModel>("leaves1");
collection.InsertOne(leaveLogic);
}
Now this is the MongoDB table that saves as a previous date.
Here you can see that my StartDate is Apr-02-2018 but it saves as Apr-01-2018 and for all date it is the same.
Can someone tell me where I am wrong?
When you create new dates with just date or date and time, it usually creates them in the same timezone as the program is.
So if you dont specify the timezone, it becomes the timezone the server is in. When you save to Mongo, the Date is serialized to UTC -> zero timezone.
Create the dates with +00:00 timezone and you should have consistent data.
It's a good practice to set your datetimes to UTC, however if you want to convert it, you can use something like this.
var date = DateTime.UtcNow;
TimeZoneInfo.ConvertTime(date, TimeZoneInfo.Local);
I have this datetime stamp from Ruby:
2017-10-06 05:11:53 UTC
This datetime stamp from JavaScript:
"2017-10-07T12:07:06.694Z"
Is there a method to which I could find out the difference in seconds?
How do I convert from a ruby timestamp to a javascript timestamp?
You could do this using Ruby with strftime or directly in javascript as demonstrated by Tavish.
var myDate = new Date('2017-10-06 05:11:53 UTC')
How do I find the difference in seconds between two timestamps with Javascript?
var past = new Date('2017-10-06 05:11:53 UTC');
var future = new Date('2017-10-07T12:07:06.694Z');
var deltaInMilliseconds = future.getTime() - past.getTime();
var deltaInSeconds = deltaInMilliseconds / 1000;
console.log(deltaInSeconds)
There are lot of ways to do so. One way is:
var myDate = new Date('2017-10-06 05:11:53 UTC')
console.log(myDate)
var myDate1 = new Date('2017-10-07T12:07:06.694Z')
console.log(myDate1)
var difference = myDate.getSeconds() - myDate1.getSeconds()
console.log(`Seconds passed: ${difference}`)
Using the following:
var timestart = $('.thisDiv').data("timestart");
var startDateTime = new Date(timestart);
to collect a date from a php file that is updating by ajax from this:
$TimeStart = date( 'Y,m,d,g,i', $TimeStart );
<div class="thisDiv" data-timestart="<?= $TimeStart ?>"></div>
var timestart = $('.thisDiv').data("timestart");
In console I'm getting the following when logging timestart and startDateTime:
2017,07,24,7,50
Invalid Date
If I paste the date that is output as follows
var startDateTime = new Date(2017,07,24,7,50);
Then it works fine. Any ideas why I'm getting Invalid Date?
Your timestart variable (JavaScript) is just a string. So it's a string 2017,07,24,7,50, and not those elements in order - which can't be used as separate parameters like new Date() expects.
Let's take a look at it!
var startDateTime = new Date(2017,07,24,7,50); // Parameters in order - all OK!
var startDateTime = new Date("2017,07,24,7,50"); // A single string - single parameter, not OK!
You need to return a proper format of dates from PHP with a format that's valid in JavaScript. Per the ECMAScript standard, the valid format that should work across all browsers is YYYY-MM-DDTHH:mm:ss.sssZ (see the reference at the bottom). To define that from PHP, you would need to format it as such
$TimeStart = date('c', $TimeStart);
This would return a format such as 2017-07-24T21:08:32+02:00.
Alternatively, you can use a splat/spread-operator ... and split the string it into elements, which I find as the better approach than above.
var timestart = $('.thisDiv').data("timestart"); // Get the string: "2017,07,24,7,50"
timestart = timestart.split(","); // Split into array
var startDateTime = new Date(...timestart); // Pass as arguments with splat-operator
Spread/splat operator in JavaScript
PHP date() documentation
ECMAScript date string (JavaScript)
You need to convert your date from string format to numbers.
var timestart = $('.thisDiv').data("timestart").split(",").map(Number);
var startDateTime = new Date(...timestart);
console.log(startDateTime)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="thisDiv" data-timestart="2017,07,24,7,50"></div>
I'm using moment to convert a date string to a date object then get the milliseconds of that date and pass it to the server as a query string
the problems is that the milliseconds I get from the javascript when I try to convert it to DateTime in C# it always gives me different date
javascript
function RedirectToOptions() {
var iBranchId = $('#ddl_Branches').val();
var strDate = $('#txt_datepicker').val();
var dtDate = moment(strDate);
var iDate = dtDate.toDate().getTime();
var capitalActionUrl = '#Html.Raw(#Url.Action("Revenue", new {BranchId = "_id_", DateTimeStamp = "_date_" }))';
var branchCapitalUrl = capitalActionUrl.replace("_id_", iBranchId);
var branchCapitalUrl = branchCapitalUrl.replace("_date_", iDate);
window.location.replace(branchCapitalUrl);
}
C#
public ActionResult Revenue(int? BranchId, double? DateTimeStamp)
{
DateTime? date = (DateTimeStamp.HasValue) ? (DateTime?)DateTimeConverter.FromUnixToDateTime(DateTimeStamp.Value) : null;
IEnumerable<RevenueDTO> revenueDTO = _Client.GetRevenue(BranchId, date);
IEnumerable<RevenueViewModel> revenue = ViewModelConverter.RevenueDTOToRevenueViewModel(revenueDTO);
List<BranchDTO> branchesDTO = _Client.GetAllBranches().ToList();
var branches = ViewModelConverter.BranchDTOToBranchesViewModelList(branchesDTO);
ViewBag.Branches = branches;
return View(revenue);
}
Converting to date time
public static DateTime FromUnixToDateTime(double UnixTimeStamp)
{
DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
dateTime = dateTime.AddMilliseconds(UnixTimeStamp);
return dateTime;
}
when I try to pass 1/5/2016 (dd/MM/yyyy formatted) when I convert it, it becomes 1/4/2016 for some reason
There is a better way to pass the date object to C# and that is using ordinary ISO 8601 standard format (e.g. 2016-01-01T12:00:00.568Z). If you call toJSON() on your date, the binder in C# should automatically convert it to C# datetime with appropriate time zone.
You will be able to see if you have a timzeone mismatch with you milliseconds in javascript easier as well than dealing with raw millisecond number.
You can read more on it here.
If you are using the epoch, then make sure all your timezones are set in UTC (and convert to local afterwards)... in Javascript:
// ...
var dtDate = moment.utc(strDate);
// ...
And in C#:
// ...
DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
// ...
I want time duration between two date time. I have the start date, start time, end date and end time. Now I have to find the difference between them.
Actually I have tried with this following code, but I got the alert like 'invalidate date'.
function myfunction()
{
var start_dt = '2013-10-29 10:10:00';
var end_dt = '2013-10-30 10:10:00';
var new_st_dt=new Date(start_dt);
var new_end_dt=new Date(end_dt);
alert('new_st_dt:'+new_st_dt);
alert('new_end_dt:'+new_end_dt);
var duration=new_end_dt - new_st_dt;
alert('duration:'+duration);
}
the alert msg like as follows:
new_st_dt:invalid date
new_end_dt: invalid date
duration:NaN
when I run in android simulator I got these alert messages.
Please help me how to get it? How to implement this?
You're passing an invalid ISO date string to that Date() constructor. It needs a form like
YYYY-MM-DDThh:mm:ss
for instance
2013-10-29T10:10:00
So you basically forgot the T to separate date and time. But even if the browser reads in the ISO string now, you would not have an unix timestamp to calculate with. You either can call
Date.parse( '2013-10-29T10:10:00' ); // returns a timestamp
or you need to explicitly parse the Date object, like
var duration=(+new_end_dt) - (+new_st_dt);
Further read: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
Try formatting you timestamps as isoformat so javascript recognizes them. (you put a "T" between the date and time). An example: '2013-10-29T10:10:00'
function dateDiff(){
var start_dt = '2013-10-29 10:10:00';
var end_dt = '2013-10-30 10:10:00';
var d1= start_dt ;
d1.split("-");
var d2= end_dt ;
d2.split("-");
var t1 = new Date(d2[0],d2[1],d2[2]);
var t2 = new Date(d1[0],d1[1],d1[2]);
var dif = t1.getTime() - t2.getTime();
var Seconds_from_T1_to_T2 = dif / 1000;
return Math.abs(Seconds_from_T1_to_T2);
}