Why is the C# parsed DateTime 7 hours ahead? - javascript

In trying to convert my local time from Javascript to C# I've poked around S/O to find some examples. While I've found a few different approaches to this, all of them render the final time as 7 hours ahead of me, which I'm not understanding.
e.g.:
var t = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(1468877118719).ToLocalTime();
Console.WriteLine(t)
7/18/2016 9:25:18 PM//<--output
or
var t = DateTime.Parse("2016-07-18T21:27:32.513Z");
Console.WriteLine(t);
7/18/2016 9:27:32 PM//output
Also, even when I simply try
var now = DateTime.Now;
Console.WriteLine(now);
7/18/2016 9:39:55 PM//the output is 7 hours ahead.
Can anyone tell me why this is happening and how to rectify it?

The machine where you run this has its local clock set to match UTC.
This is very common on servers and *nix workstations, including OS X.

What you're seeing is the output of the UTC value.
Change
Console.WriteLine(t);
to
Console.WriteLine(t.ToLocalTime());
Of course, this will only make a difference in the second case. You're already calling ToLocalTime() in the first instance.

Related

Getting a portion of a sorted array from start value to end value

I'm pretty new to javascript and I need to get a portion (slice) of a sorted array (Numbers, timestamps basically) by start_value and end_value.
For example, let's say I have an array of random timestamps from last month, and I want to get all timestamps between two weeks ago and a week ago.
This is a pretty simple algorithm to write (using a binary search) but I don't want to mess up my code with these computations.
I've been searching for a way to do this in javascript but haven't found any.
Thanks for any future help :)
Perhaps use filter?
var dates = [123, 234, 456, 468, 568, 678];
var min = 300;
var max = 500;
var inRange = dates.filter(function(date) {
return min < date && date < max;
});
console.log(inRange);
On the plus side, this doesn't even need them to be sorted. On the down side, it probably won't be as fast as a well-implemented binary search for the relevant start and end points. Unless you've got some really harsh performance requirements I don't think that'll matter.
Ok, I found a pure js library called binarysearch that has exactly what I'm looking for: https://www.npmjs.com/package/binarysearch. It has rangeValue function which accepts non-existing numbers as start-end. Seems to be working :)

Javascript Date/Time Parsing, UTC to Local Time Broke

I have a strange timezone/date formatting issue that recently came up with some new code, and what makes it more strange is that it only affects two months - August and September.
The code takes a date string with UTC time formatted like this:
10-06-2017 09:29:15
And converts it to a new string with the same format but with local time. The zeroPad function ensures that the format remains the same.
We implemented it in March and everything worked fine. It's within Classic ASP on IIS9/Server 2012.
As soon as we got to August, it broke. 08-10-2017 09:33:06 becomes 12-09-2016 20:33:06.
Can anyone see what I've done wrong?
function jsConvert(dateString) {
var patterns = dateString.split(/[\-\s:]/g);
var date = new Date(parseInt(patterns[2]),
parseInt(patterns[0]) - 1,
parseInt(patterns[1]),
parseInt(patterns[3]),
parseInt(patterns[4]),
parseInt(patterns[5]));
date.setTime(date.getTime() - getTimezoneOffset() * 60 * 1000);
var result = zeroPad(date.getMonth() + 1);
result += '-' + zeroPad(date.getDate());
result += '-' + date.getFullYear();
result += ' ' + zeroPad(date.getHours());
result += ':' + zeroPad(date.getMinutes());
result += ':' + zeroPad(date.getSeconds());
return result;
}
function zeroPad(number) {
return (number < 10) ? '0' + number : number;
}
What are the units of time in your getTimezoneOffset() function?
Your code is written as though the getTimezoneOffset() function returns a number of minutes, since you are multiplying by 60 and then 1000, to get millseconds.
But if your getTimezoneOffset is returning seconds, you will be over-doing the multiplication and therefore jumping back too far in time.
I think it would have to be milliseconds, to jump back the distance you are getting. #CBroe above mentions that perhaps you mean the builtin getTimezoneOffset function, which is indeed in minutes. Perhaps you have a separate getTimezoneOffset function defined in your code elsewhere, that returns an answer in milliseconds? In which case CBroe's answer fixes it.
My next suggestion would be to add lines of debugging code
For example, could you add the following?
At the beginning, add console.log("A",dateString).
After var patterns = dateString.split(/[\-\s:]/g); add a line console.log("B",patterns);.
After var date = ...(patterns[5])); add a line console.log("C",date);.
After date.setTime...1000); add a line console.log("D",date); console.log("E",getTimezoneOffset());.
If you show us the output of these lines, we should be able to pinpoint the problem easily. I have included item E because I am just wondering if there is yet another getTimezoneOffset() function in your system, which we are not aware of, or something. Seeing its value will help reassure everyone.
Meanwhile can you confirm the time zone you are running the code in? I am guessing it is in the USA rather than Europe, from your preference for putting month before the day?
So as it turns out this is a known, albeit obscure issue. It has to do with the fact that parseInt assumes that numbers with leading zeros are NOT base 10, but instead radix. It's well documented here: Javascript parseInt() with leading zeros
Once I made the change to:
parseInt(patterns[2]**, 10**);
All was good.
Thanks for the input.

JavaScript: Multi Time Zones Clocks

I want to display 3 clocks from 3 different time zones using JavaScript.
I browsed around the web searching for a simple solution but all I found was long scripts and .js extensions, all those to complete a simple task.
Is there an easy way to do this? do I really have to add an additional JS file to complete this task?
Thanks in advance to the helpers!
Is there an easy way to do this?
Yes.
do I really have to add an additional JS file to complete this task?
No. However, time handling in JS is difficult, since it has no really cross-browser-safe date/timestring parsing and formatting methods. It can be helpful to use a library for that, however that won't be necessary for your clock.
// all three clocks represent current time
var clock1 = new Date(); // current moment
var clock2 = new Date();
var clock3 = new Date();
// for outputting, adjust them
// leave clock1 in UTC
clock2.setHours(clock2.getHours() + 3); // UTC+3
clock3.setHours(clock3.getHours() - 5); // UTC-5
// now for display, use these values:
clock1.getUTCHours();
clock1.getUTCMinutes();
clock1.getUTCSeconds();
clock2.getUTCHours();
clock2.getUTCMinutes();
clock2.getUTCSeconds();
clock3.getUTCHours();
clock3.getUTCMinutes();
clock3.getUTCSeconds();

Ways to simplify an array of objects that is repeated several times

I wonder if I can simplify and use less lines of code for this purpose:
I have a class called "worker", and that class has a method that reads the properties (name, age, etc...) from a series of simple arrays.
Until there, everything is fine. Now, one of the properties that I want to add is a boolean value that makes reference to which months of the year the worker is active. For the moment, I have solved it like this:
var months_worker_1 = [{"jan":true},{"feb":true},{"mar":true},{"apr":false}] //and so on
And then, my property reads months_worker_1, but I have one array like that for each worker. I wonder if there is a way to do this that requires less lines of code, like for example, create a "master" array with all the months of the year, and in the array for each worker, specify just the months they are working. Those months become "true", and the rest of months become "false" automatically without specifying so... I have been scratching my head for some time, and for the moment only my current system is working fine, but I am guessing that there must be a simpler way...
Thanks very much!
Edit: I clarify, there is no "big picture". I am just doing some exercises trying to learn javascript and this one woke my interest, because the solution I thought seems too complicated (repeating same array many times). There is no specific goal I need to achieve, I am just learning ways to do this.
A really nice trick that I use sometimes is to use a binary number to keep track of a fixed amount of flags, and convert it to a decimal for easier storage / URL embedding / etc. Let's assume Mark, a user, is active all months of the year. Considering a binary number, in which 1 means "active" and 0 inactive, Mark's flag would be:
111111111111 (twelve months)
if Mark would only be active during january, february and december, his flag value would be:
11000000001
Checking if Mark is active during a specific months is as simple as checking if the character that corresponds to that month's index in Mark's flag is 1 or 0.
This technique has helped me in the past to send values for a large number of flags via URLs, while also keeping the URL reasonably short. Of course, you probably don't need this, but it's a nice thing to know:
Converting from binary to decimal is easy in JS:
parseInt(11000000001, 2).toString(10); // returns 1537
And the reverse:
parseInt((1537).toString(2)); // returns 11000000001
Edit
You could just as easily use an array made out of the month numbers:
var months_worker_1 = [1, 2, 3]; // this would mean that the user is active during january, february and march

accurate timing range with javascript

I'm working on a html5 sound fader widget using the Soundmanager2 library, and I have a function that should be setting a variable to interpolate between 0-100 across 15 seconds, but it takes more than 15 seconds the first time and then less each time after. That inconsistency is driving me nuts.
my js is here: http://wesww.com/nic/peasoup9/js/soundfader.js
CODE:
I'm setting a 15 second duration:
function fadeOutSound(soundObject) {
var fadeLengthInSeconds = 15;
And am doing some math here:
if(soundObject.volume < maximumVolume) {
var progressRatio = deltaTime / soundObject.fadeLength;
var actualProgress = progressRatio * maximumVolume;
soundObject.setVolume( soundObject.volume + actualProgress );
Thanks for any help / tips you might have! If I can add any info/code to make clearer, please let me know
Edit: I ended up going with a self-adjusting timer, such as this: http://www.sitepoint.com/creating-accurate-timers-in-javascript/
All numbers in JavaScript are, by definition, 64-bit floats. The various JavaScript-engines, however, usually type-cast them into simpler number formats if possible (I'm pretty sure at least V8 does this.)
While I haven't played with it myself, it seem Typed Arrays are currently the best trick to make maths perform on a larger scale. It only works on "modern" browsers, though.
You may want to take a look at the division.
I am suspecting there is a error like this:
10/3 = 3
where all numbers are casted to integer.

Categories