Java script has Date.UTC method which is used like that Date.UTC(2004,3,1) is there the same in .NET?
I was trying to use DateTime.ToFileTimeUtc() but it is returning differs value.
For example if i have this date
javascript Date.UTC(2004,3,1) will return this 1075766400000
but DateTime.ToFileTimeUtc() will return this 127175616000000000
Need help
UPDATE
when i am using this
TimeSpan timeSpan = new DateTime(2004, 3, 1, 0, 0, 0, DateTimeKind.Utc) - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
long milliSeconds = (long)timeSpan.TotalMilliseconds; // equal to 1073088000000
the milliSeconds equal to 1073088000000 but in case of Date.UTC(2004,3,1) it is 1075766400000 http://jsfiddle.net/M3aJQ/
the difference is 00:04:27.8400000
As #Jon Marting says;
DateTime Constructor (Int32, Int32, Int32, Int32, Int32, Int32, DateTimeKind)
and use DateTimeKind.Utc
public DateTime(
int year,
int month,
int day,
int hour,
int minute,
int second,
DateTimeKind kind
)
The DateTime method ToUniversalTime() will convert to UTC correctly.
DateTime now = DateTime.Now;
DateTime utc = now.ToUniversalTime();
of course for .Now in UTC you can also use:
DateTime utcnow = DateTime.UtcNow;
DateTime.ToFileTimeUtc() uses a different epoch to Date.UTC() in JavaScript. That's why you get different answers. According to MSDN it returns the "number of 100-nanosecond intervals that have elapsed since 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC)".
Whereas, I believe JavaScript's Date.UTC method returns the number of milliseconds since midnight of January 1, 1970.
You could do it yourself, something like this in .net:
TimeSpan timeSpan = new DateTime(2004, 3, 6, 0, 0, 0, DateTimeKind.Utc) - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
long milliSeconds = (long)timeSpan.TotalMilliseconds;
Related
I have a date in the format dd.mm.yyyy
I use a function to convert this date to MM-DD-YYYY
stringToStringDateFormat(objectData: any): string {
return moment(objectData, 'DD.MM.YYYY').format('MM-DD-YYYY');
}
I want to set hours minutes and seconds to 0
ad send the date in ISO format so i used the following code :
new Date(new Date(this.stringToStringDateFormat("19.07.2021")).setUTCHours(0,0,0,0)).toISOString();
yet the issue I have is I get a different day
for example in this case I get 2021-07-18T00:00:00.000Z
while in reality, it should be 2021-07-19T00:00:00.000Z
how can I get my code to get me the same date I provided and not the date -1 ?
Here using Date.UTC() and adjusting the month to account for zero index.
const [d, m, y] = `19.07.2021`.split('.').map(Number);
console.log(new Date(Date.UTC(y, (m - 1), d)).toISOString()); // months are 0 indexed
Created a new function that sets the hours, minutes, seconds and milliseconds to 0 and returns the date string in the correct format. See this answer for a more detailed look on the methods I used.
function stringToStringDateFormatStartDay(objectData) {
const newD = moment(objectData, "DD.MM.YYYY").utcOffset(0).set({
hour: 0,
minute: 0,
second: 0,
millisecond: 0
});
newD.toISOString();
newD.format("MM-DD-YYYY");
return newD;
}
const d = stringToStringDateFormatStartDay("19.07.2021");
console.log(d)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Parsing with a library to create an interim unsupported format then parsing with the built–in parser is not a good idea.
If you just want to reformat dd.mm.yyyy as yyyy-mm-ddT00:00:00Z then just reformat the string, there is no need to convert to Date object or use a library:
function reformatTimestamp(s) {
return `${s.split(/\D/).reverse().join('-')}T00:00:00Z`;
}
console.log(reformatTimestamp('19.07.2021'));
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 have a string which contains DateTime as "20140121230000" . If i try to convert this into a Date.
var oDate = new Date(20140121230000);
i'm getting the year as 2068! Is there a way to convert this into a Date which is of year 2014, month 01 Date 21 Time 23:00:00 ?
Is it possible to directly convert this without doing any parsing in the string ?
Unless you use a library there is no way to convert the value without manually splitting the string.
var year = +oDate.slice( 0, 4);
var month = +oDate.slice( 4, 2) - 1; // Month is zero-based.
var day = +oDate.slice( 6, 2);
var hour = +oDate.slice( 8, 2);
var minute = +oDate.slice(10, 2);
var second = +oDate.slice(12, 2);
// This will interpret the date as local time date.
var date = new Date(year, month, day, hour, minute, second);
// This will interpret the date as UTC date.
var utcDate = Date.UTC(year, month, day, hour, minute, second);
The constructor you used takes millisecond since 1st Jan, 1970, try using :
var oDate = new Date(2014, 01, 21, 23, 00, 00, 00);
Note, month 01 will be Feb, not Jan.
Constructing a Date object with a string
new Date(string)
expects a date string that Date.parse can understand:
ISO 8601 (e.g. 2011-10-10T14:48:00), or
RFC2822 (e.g., Mon, 25 Dec 1995 13:30:00 GMT)
See MDN for more information on Date and Date.parse.
Yours is not a recognized format. You can either
reformat the string to fit one of the formats above
split the string manually and call Date with individual parameters, as in new Date(year, month, day, hour, minute, second, millisecond)
use a library like moment.js
Using moment.js would look something like this:
moment("20140121230000", "YYYYDDMMHHmmss")
See moment.js string + format for more information about the format syntax.
Given '20140121230000', you can split it into bits and give it to the Date constructor:
function parseSToDate(s) {
var b = s.match(/\d\d/g) || [];
return new Date( (b[0] + b[1]), --b[2], b[3], b[4], b[5], b[6]);
}
console.log(parseSToDate('20140121230000'));
I am a trying to create a Javascript date object from a time in milliseconds computed from GMT0 (or UTC).
I use the following code for a time located in 2013 (as verifiable here):
var t = new Date(Date.UTC(0, 0, 0, 0, 0, 0, 0));
t.setMilliseconds(1383447600000);
but when I call the following:
alert(t.getFullYear());
alert(t.getUTCFullYear());
I am getting 1943... and not 2013!
Why? And how to solve this? Thanks!
The JsFiddle is: http://jsfiddle.net/EVf72/
Short Answer: Use setTime instead of setMilliseconds.
Long Answer:
The problem is that your starting date is incorrect. The value of 1383447600000 is the number of seconds since epoch 0 (January 1, 1970, 00:00:00 UTC), but your starting date is not epoch 0! Instead, it is the year 1899:
> var t = new Date(Date.UTC(0, 0, 0, 0, 0, 0, 0));
> console.log(t.getFullYear());
1899
When you then use setMilliseconds and provide a range over 999, it will convert the value into the appropriate numbers of years, days, hours, seconds, and milliseconds and add it to the current date.
1383447600000 corresponds to a little over 43 years. So you're basically telling JavaScript to add a little over 43 years to 1899, which gives you 1943.
From the documentation for setMilliseconds:
If you specify a number outside the expected range, the date information in the Date object is updated accordingly. For example, if you specify 1005, the number of seconds is incremented by 1, and 5 is used for the milliseconds.
If you had instead provided the correct starting point to Date.UTC so that it matches epoch 0, you would have received the correct answer:
> var t = new Date(Date.UTC(1970, 0, 0, 0, 0, 0, 0)); //First param is year
> t.setMilliseconds(1383447600000);
> console.log(t.getFullYear());
2013
But instead of doing all of that, you can simply use setTime:
> var t = new Date();
> t.setTime(1383447600000);
> console.log(t.getFullYear());
2013
So to recap, the following are functionally equivalent:
> var t = new Date(Date.UTC(1970, 0, 0, 0, 0, 0, 0)); //First param is year
> t.setMilliseconds(1383447600000);
> console.log(t.getFullYear());
2013
and
> var t = new Date();
> t.setTime(1383447600000);
> console.log(t.getFullYear());
2013
But if you are dealing with milliseconds since epoch 0, you either need to use setTime, or make sure that you actually start with epoch 0 (using Date.UTC) if you are going to be using setMilliseconds.
It's happening because Date.UTC(0, 0, 0, 0, 0, 0, 0) is a large negative number. That gets you a time far in the past. When you call setMilliseconds() the semantics are that you're updating the millisecond value on that in-the-past time. That rolls that time forward, but it's still 70 years in the past because you started far, far back.
The .setTime() API on Date instances forces the entire date to be set to the provided timestamp value, overwriting the previous value completely.
Date.UTC(year,month,day,hours,minutes,seconds,millisec) returns the number of milliseconds in a date string since midnight of January 1, 1970, according to universal time. You need to fill in the desired date for Date.UTC(2013, 1, 1, ...).
Using the following code in .NET
Input: "2011-09-14 00:00:00.0000000" (From an SQL datebase loaded into a Date datetype becoming #9/14/2011#)
<Extension()>
Public Function ToEpoch(value As Date) As Double
Dim span As TimeSpan = (value - New Date(1970, 1, 1, 0, 0, 0, 0).ToLocalTime)
Return span.TotalMilliseconds
End Function
And this in JavaScript
var StartDate = new Date(<%= StartDate() %>);
Resulting in this output
var StartDate = new Date(1315922400000);
It appears that only for this specific input the StartDate (on the javascript side) is exactly one hour off.
Resulting in the JavaScript datetime of: Tue Sep 13 23:00:00 UTC+1000 2011
If I input a value like Date.Now it appears to function correctly.
I assume I'm missing something fundamental?
Seems to me that unix epoch is Jan 1, 1970, UTC.
In light of that, your creation of the Date and then conversion to local time is somewhat backwards. What you need to do is convert the variable time value to UTC.
<Extension()>
Public Function ToEpoch(value As Date) As Double
Dim span As TimeSpan = (value.ToUniversalTime -
New System.DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))
Return span.TotalMilliseconds
End Function
You may think the two conversions are equivalent, but they may not be, as explained in
http://blogs.msdn.com/b/oldnewthing/archive/2003/10/24/55413.aspx .
I suspect the two dates have different daylight savings values. See if the following calls to IsDaylightSavingTime() return the same values:
Dim dt As Date = new Date(2011, 9, 14)
Dim epoch As Date = new Date(1970, 1, 1)
dt.IsDaylightSavingTime()
epoch.IsDaylightSavingTime()