IE/Edge Does not return a parsable string with .toLocaleTimeString()

Recently, I was trying to parse the time portion of a date. I used split() to chop time string into hours, minutes, seconds, etc. and attempted to parseInt() the hour portion of the split array like so:

<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">Click me to parse the current time</button>
<p id="demo"></p>

function myFunction() {
var str = new Date().toLocaleTimeString();
var parts= str.split(":");
var hour= parseInt(parts[0]);
document.getElementById("demo").innerHTML = parts+"
----
"+parts[0]+"
----
"+hour;}
//output:
//4,00,39,PM
//----
//4
//----
//NaN

</body>
</html>

The code above works in every other browser except Internet Explorer (11+) and Edge (all as of v 38.14393.0.0).

So what’s the problem? It turns out, that IE/Edge also includes some hidden formatting characters (in this case, one indicating left-to-right). Simply clearing that formatting string does the trick like so:


<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">Click me to parse the current time</button>
<p id="demo"></p>

function myFunction() {
var str = new Date().toLocaleTimeString().replace(/\u200E/g, '');
var parts= str.split(":");
var hour= parseInt(parts[0]);
document.getElementById("demo").innerHTML = parts+"
----
"+parts[0]+"
----
"+hour;}
//output:
//4,00,39,PM
//----
//4
//----
//4

</body>
</html>

Javascript Method ‘getElapsedTime(date)’: Get The Amount of Time That Has Elapsed

Here is a simple Javascript method you can can call to determined how much time has elapsed between a specified date  and now. In other words, you can use it to display how “long ago” something happened.

The Use Case

A perfect use case would be a custom Twitter “ticker” (although those aren’t ‘allowed’ anymore.) Let’s say you had a website with a custom Twitter “ticker” that cycles through displaying the 5 most recent tweets  (a.k.a statuses) one at a time. It would make sense that your tweets also displayed how old they are such as: “1 day ago” or “About 3 hours ago”.

Continue reading

Correcting Dates That Have Been Serialized to JSON

The Problem

The issue with dates in JSON, is that whenever you serialize, say a C# DateTime object, the date comes out in an unexpected format. Observe the output when a date of June 10, 2013 8:45:43PM is serialized to JSON:

DateTime date = new DateTime(2013, 6, 10, 20, 45,43);
String jsonDate = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(date);
// jsonDate = "/Date(1370897143000)/";

In this post we’ll look at how to fix this so that the date can be displayed or manipulated properly in the front-end.

Continue reading