JavaScript Date Validation when using firefox [duplicate] - javascript

I am creating a datetime string that looks like this: 2010-07-15 11:54:21
And with the following code I get invalid date in Firefox but works just fine in Chrome
var todayDateTime = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + seconds;
var date1 = new Date(todayDateTime);
In firefox date1 is giving me an invalid date, but in chrome its working just fine what would the main cause be?

You can't instantiate a date object any way you want. It has to be in a specific way. Here are some valid examples:
new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
or
d1 = new Date("October 13, 1975 11:13:00")
d2 = new Date(79,5,24)
d3 = new Date(79,5,24,11,33,0)
Chrome must just be more flexible.
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
From apsillers comment:
the EMCAScript specification requires exactly one date format (i.e., YYYY-MM-DDTHH:mm:ss.sssZ) but custom date formats may be freely supported by an implementation: "If the String does not conform to that [ECMAScript-defined] format the function may fall back to any implementation-specific heuristics or implementation-specific date formats." Chrome and FF simply have different "implementation-specific date formats."

This works in all browsers -
new Date('2001/01/31 12:00:00 AM')
new Date('2001-01-31 12:00:00')
Format: YYYY-MM-DDTHH:mm:ss.sss
Details: http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15

Option 1 :
Suppose your timestring has a format that looks like this :
'2016-03-10 16:00:00.0'
In that case, you could do a simple regex to convert it to ISO 8601 :
'2016-03-10 16:00:00.0'.replace(/ /g,'T')
This would procude the following output :
'2016-03-10T16:00:00.0'
This is the standard datetime format, and thus supported by all browsers :
document.body.innerHTML = new Date('2016-03-10T16:00:00.0') // THIS IS SAFE TO USE
Option 2 :
Suppose your timestring has a format that looks like this :
'02-24-2015 09:22:21 PM'
Here, you can do the following regex :
'02-24-2015 09:22:21 PM'.replace(/-/g,'/');
This, too, produces a format supported by all browsers :
document.body.innerHTML = new Date('02/24/2015 09:22:21 PM') // THIS IS SAFE TO USE
Option 3 :
Suppose you have a time string that isn't easy to adjust to one of the well-supported standards.
In that case, it's best to just split your time string into different pieces and use them as individual parameters for Date :
document.body.innerHTML = new Date(2016, 2, 26, 3, 24, 0); // THIS IS SAFE TO USE

This works in most browsers as well
new Date('2001/01/31 12:00:00')
That is the format of
"yyyy/MM/dd HH:mm:ss"

If you still want to create date using dashes, you can use this format:
var date = new Date('2013-08-31T17:00:00Z')
But bear in mind, that it creates time according to UTC. Meaning, if you live in GMT+3 (3 hours ahead of GMT) timezone, it will add this timezone offset to the time. So the above example will have this value, if GMT+3 (note that it is hour 20:00 and not 17:00):
Sat Aug 31 2013 20:00:00 GMT+0300 (FLE Standard Time)
Be sure to add 'Z' letter at the end, because otherwise Chrome and Firefox will parse the string differently (one will add time offset and the other won't).

I was having a similar issue in both Firefox and Safari when working with AngularJS. For example, if a date returned from Angular looked like this:
2014-06-02 10:28:00
using this code:
new Date('2014-06-02 10:28:00').toISOString();
returns an invalid date error in Firefox and Safari. However in Chrome it works fine. As another answer stated, Chrome is most likely just more flexible with parsing date strings.
My eventual goal was to format the date a certain way. I found an excellent library that handled both the cross browser compatibility issue and the date formatting issue. The library is called moment.js.
Using this library the following code works correctly across all browsers I tested:
moment('2014-06-02 10:28:00').format('MMM d YY')
If you are willing to include this extra library into your app you can more easily build your date string while avoiding possible browser compatibility issues. As a bonus you will have a good way to easily format, add, subtract, etc dates if needed.

This should work for you:
var date1 = new Date(year, month, day, hour, minute, seconds);
I had to create date form a string so I have done it like this:
var d = '2013-07-20 16:57:27';
var date1 = new Date(d.substr(0, 4), d.substr(5, 2), d.substr(8, 2), d.substr(11, 2), d.substr(14, 2), d.substr(17, 2));
Remember that the months in javascript are from 0 to 11, so you should reduce the month value by 1, like this:
var d = '2013-07-20 16:57:27';
var date1 = new Date(d.substr(0, 4), d.substr(5, 2) - 1, d.substr(8, 2), d.substr(11, 2), d.substr(14, 2), d.substr(17, 2));

Simple Solution, This works with All Browsers,
var StringDate = "24-11-2017"
var DateVar = StringDate.split("-");
var DateVal = new Date(DateVar[1] + "/" + DateVar[0] + "/" + DateVar[2]);
alert(DateVal);

One situation I've run into was when dealing with milliseconds. FF and IE will not parse this date string correctly when trying to create a new date.
"2014/11/24 17:38:20.177Z"
They do not know how to handle .177Z. Chrome will work though.

This is what worked for me on Firefox and Chrome:
// The format is 'year-month-date hr:mins:seconds.milliseconds'
const d = new Date('2020-1-4 12:00:00.999')
// we use the `.` separator between seconds and milliseconds.
Good Luck...

There is a W3C specification defining possible date strings that should be parseable by any browser (including Firefox and Safari):
Year:
YYYY (e.g., 1997)
Year and month:
YYYY-MM (e.g., 1997-07)
Complete date:
YYYY-MM-DD (e.g., 1997-07-16)
Complete date plus hours and minutes:
YYYY-MM-DDThh:mmTZD (e.g., 1997-07-16T19:20+01:00)
Complete date plus hours, minutes and seconds:
YYYY-MM-DDThh:mm:ssTZD (e.g., 1997-07-16T19:20:30+01:00)
Complete date plus hours, minutes, seconds and a decimal fraction of a
second
YYYY-MM-DDThh:mm:ss.sTZD (e.g., 1997-07-16T19:20:30.45+01:00)
where
YYYY = four-digit year
MM = two-digit month (01=January, etc.)
DD = two-digit day of month (01 through 31)
hh = two digits of hour (00 through 23) (am/pm NOT allowed)
mm = two digits of minute (00 through 59)
ss = two digits of second (00 through 59)
s = one or more digits representing a decimal fraction of a second
TZD = time zone designator (Z or +hh:mm or -hh:mm)
According to YYYY-MM-DDThh:mmTZD, the example 2010-07-15 11:54:21 has to be converted to either 2010-07-15T11:54:21Z or 2010-07-15T11:54:21+02:00 (or with any other timezone).
Here is a short example showing the results of each variant:
const oldDateString = '2010-07-15 11:54:21'
const newDateStringWithoutTZD = '2010-07-15T11:54:21Z'
const newDateStringWithTZD = '2010-07-15T11:54:21+02:00'
document.getElementById('oldDateString').innerHTML = (new Date(oldDateString)).toString()
document.getElementById('newDateStringWithoutTZD').innerHTML = (new Date(newDateStringWithoutTZD)).toString()
document.getElementById('newDateStringWithTZD').innerHTML = (new Date(newDateStringWithTZD)).toString()
div {
padding: 10px;
}
<div>
<strong>Old Date String</strong>
<br>
<span id="oldDateString"></span>
</div>
<div>
<strong>New Date String (without Timezone)</strong>
<br>
<span id="newDateStringWithoutTZD"></span>
</div>
<div>
<strong>New Date String (with Timezone)</strong>
<br>
<span id="newDateStringWithTZD"></span>
</div>

In fact, Chrome is more flexible to deal with different string format. Even if you don't figure out its String format, Chrome still can successfully convert String to Date without error. Like this:
var outputDate = new Date(Date.parse(inputString));
But for Firefox and Safari, things become more complex. In fact, in Firefox's document, it already says: (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse)
A string representing an RFC2822 or ISO 8601 date (other formats may be used, but results may be unexpected).
So, when you want to use Date.parse in Firefox and Safari, you should be careful. For me, I use a trick method to deal with it. (Note: it might be not always correct for all cases)
if (input.indexOf("UTC") != -1) {
var tempInput = inputString.substr(0, 10) + "T" + inputString.substr(11, 8) + "Z";
date = new Date(Date.parse(tempInput));
}
Here it converts 2013-08-08 11:52:18 UTC to 2013-08-08T11:52:18Z first, and then its format is fit words in Firefox's document. At this time, Date.parse will be always right in any browser.

In Firefox, any invalid Date is returned as a Date object as Date 1899-11-29T19:00:00.000Z, therefore check if browser is Firefox then get Date object of string "1899-11-29T19:00:00.000Z".getDate(). Finally compare it with the date.

I have used following date format and it's working in all browser.
var target_date = new Date("Jul 17, 2015 16:55:22").getTime();
var days, hours, minutes, seconds;
var countdown = document.getElementById("countdown");
remaining = setInterval(function () {
var current_date = new Date().getTime();
var seconds_left = (target_date - current_date) / 1000;
days = parseInt(seconds_left / 86400);
seconds_left = seconds_left % 86400;
hours = parseInt(seconds_left / 3600);
seconds_left = seconds_left % 3600;
minutes = parseInt(seconds_left / 60);
seconds = parseInt(seconds_left % 60);
countdown.innerHTML = "<b>"+days + " day, " + hours + " hour, "
+ minutes + " minute, " + seconds + " second.</b>";
}, 1000);

Related

JavaScript setHours() and getHours() [duplicate]

I am trying to subtract hours from a given date time string using javascript.
My code is like:
var cbTime = new Date();
cbTime = selectedTime.setHours(-5.5);
Where selectedTime is the given time (time that i pass as parameter).
So suppose selectedTime is Tue Sep 16 19:15:16 UTC+0530 2014
Ans I get is : 1410875116995
I want answer in datetime format.
Am I doing something wrong here? Or there is some other solution?
The reason is that setHours(), setMinutes(), etc, take an Integer as a parameter. From the docs:
...
The setMinutes() method sets the minutes for a specified date
according to local time.
...
Parameters:
An integer between 0 and 59, representing the minutes.
So, you could do this:
var selectedTime = new Date(),
cbTime = new Date();
cbTime.setHours(selectedTime.getHours() - 5);
cbTime.setMinutes(selectedTime.getMinutes() - 30);
document.write('cbTime: ' + cbTime);
document.write('<br>');
document.write('selectedTime: ' + selectedTime);
Well first off setting the hours to -5.5 is nonsensical, the code will truncate to an integer (-5) and then take that as "five hours before midnight", which is 7PM yesterday.
Second, setHours (and other functions like it) modify the Date object (try console.log(cbTime)) and return the timestamp (number of milliseconds since the epoch).
You should not rely on the output format of the browser converting the Date object to a string for you, and should instead use get*() functions to format it yourself.
According to this:
http://www.w3schools.com/jsref/jsref_sethours.asp
You'll get "Milliseconds between the date object and midnight January 1 1970" as a return value of setHours.
Perhaps you're looking for this:
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_sethours3
Edit:
If you want to subtract 5.5 hours, first you have to subtract 5 hours, then 30 minutes. Optionally you can convert 5.5 hours to 330 minutes and subtract them like this:
var d = new Date();
d.setMinutes(d.getMinutes() - 330);
document.getElementById("demo").innerHTML = d;
Use:
var cbTime = new Date();
cbTime.setHours(cbTime.getHours() - 5.5)
cbTime.toLocaleString();
try this:
var cbTime = new Date();
cbTime.setHours(cbTime.getHours() - 5.5)
cbTime.toLocaleString();

Javascript time difference

I am trying to simply calculate the time difference of 5:30:00 - 2:30:00. Obviously this should result in 3:00:00
However when I execute following code in console
var a = new Date(0,0,0,5,30,0)
var b = new Date(0,0,0,2,30,0)
var c = new Date(a-b)
console.log(c.getHours() + ":" + c.getMinutes() + ":" + c.getSeconds())
The result is 4:00:00.
What is causing this problem? And how should I handle it?
Date constructor is not suitable to either represent or deal the time spans.
There are no built-in tools to handle time spans in JS, so you need to implement one yourself.
Thankfully the time string -> seconds conversion is trivial:
const timeToSec = time => time.split(':').reduce((acc, v) => acc * 60 + parseInt(v), 0);
Then you can deal with seconds:
const diffInSeconds = timeToSec('5:30:00') - timeToSec('2:30:00'); // 10800
The reverse transformation of seconds -> time string is also trivial (and tbh it's simple reversed of the timeToSec implementation) and I'm leaving it as a home work.
The reason why people get different results is timezone.
When you calculate c as the difference between two dates, you actually get a date relative to 01.01.1970. In this case, when you do:
console.log(c);
You get something like:
1970-01-01T03:00:00.000Z
This is in UTC Date format.
But now if you would display c in the local time zone:
console.log(c.toLocaleDateString()+ ' ' + c.toLocaleTimeString());
... then you get maybe this:
1-1-1970 04:00:00
If you then take the hours of that date with getHours(), you get them from the date/time as it is in your time zone, in your case you are on GMT+1, which means the outcome is 4.
To avoid this time zone conversion, use the UTC versions of the getXXXX functions, like getUTCHours. Note that some time zones have non-integer hour differences with UTC (with an half-hour part), so they would need to use getUTCMinutes as well.
Be aware that converting date differences to Date format will start to give wrong results when you cover larger spans, crossing 29 February, ...etc. Differences are best calculated by taking the date differences (in milliseconds) without conversion to Date. From there it is straightforward to calculate the number of seconds, minutes, ...etc.
I would like to assume that your question is not merely about the difference between two numbers, but it is a real problem.
Then, the answer is: without specifying the day(s), the difference between two hours is meaningless, you must always specify which day(s) you are talking about.
For example Europe, Berlin:
Sunday, 27 March 2016, 02:00:00 clocks were turned
forward 1 hour.
Like in your example, this would lead to pay someone 1 hour more than it had worked...
Sunday, 30 October 2016, 03:00:00 clocks are turned backward 1 hour
..calculating the same interval Sunday, 30 October 2016 would do the opposite.
Moreover, be aware that daylight saving time has become standard in the U.S., Canada, and most European countries. However, most of the world doesn't even use it.
Moreover, during the past, starting day and ending day of saving time has been changed from year to year, and the starting hour has been also changed, i.e. you cannot assume always 2.00 at night - so reconstruct an interval without knowing this information would not lead to a correct result.
A possible solution to calculate correctly a duration, is always to store next the Local Date/Time also the UTC Date/Time and do the calculation keeping both in account, so you have both the Timezone and the Daylight Saving Time Shift to get back the exact start date/time and ending date/time.
If you don't have this information already stored, then you should retrieve them, for example, from a online Time Database.
usage
node time_diff.js 5:30:00 2:30:00
will output: 03:00:00
code of time_diff.js:
#!/usr/bin/env node
if (!process.argv[2] || !process.argv[3]) {
console.log('usage: time_diff hh:mm:ss hh:mm:ss');
process.exit(1);
}
const timeToSec = (time) => time.split(':').reduce((acc, v) => acc * 60 + parseInt(v), 0);
const diffInSeconds = (time1, time2) => timeToSec(time2) - timeToSec(time1);
const hhmmss = (secs) => {
var minutes = Math.floor(secs / 60);
secs = secs % 60;
var hours = Math.floor(minutes / 60);
minutes = minutes % 60;
return pad(hours) + ":" + pad(minutes) + ":" + pad(secs);
function pad(num) {
return ("0" + num).slice(-2);
}
};
try {
console.log(hhmmss(diffInSeconds(process.argv[3], process.argv[2])));
}
catch (err) {
console.log('usage: time_diff hh:mm:ss hh:mm:ss');
process.exit(1);
}
Try this simple plugin to get time differences.
https://github.com/gayanSandamal/good-time
import the goodTimeDiff method from good-time.js to your project
import {goodTimeDiff} from './scripts/good-time.js'
declare an object to give settings like below. let settings = {}
now assign time values to the declared object variable. *time must be in standard format and must be a string! *'from' is optional the default value will be the browser current time.
let settings = {
'from': '2019-01-13T00:00:29.251Z',
'to': '2018-09-22T17:15:29.251Z'
}
now calllback the method called goodTimeDiff() and pass the settings object variable as a parameter.
goodTimeDiff(settings)
Finally assign the method to any variable you want.
let lastCommentedTime = goodTimeDiff(timeSettings)
a - b results in three hours, but in milliseconds. You just need to convert milliseconds to hours (which is not new Date(milliseconds)).
try: (a-b)/1000/60/60
Formatted:
var a = new Date(0,0,0,5,30,0)
var b = new Date(0,0,0,2,30,0)
var diff = (a.getTime()-b.getTime())
var h = Math.floor(diff/1000/60/60)
var m = ('0' + Math.floor((diff/1000/60)%60) ).substr(-2)
var s = ('0' + Math.floor((diff/1000)%60) ).substr(-2)
console.log(h + ':' + m + ':' + s)
EDIT
For those who want to treat a time span as a date... just get the UTC date, which means Coordinated Universal Time. In other words, don't use timezone aware methods:
var a = new Date(0,0,0,5,30,0)
var b = new Date(0,0,0,2,30,0)
var c = new Date(a-b)
console.log(c.getUTCHours() + ":" + c.getUTCMinutes() + ":" + c.getUTCSeconds())
Be aware though, this will fall apart on edge cases...

How do show my javascript date object in users local time, across various browsers?

I have a project where Im reading JSON data and it contains a date string that Im getting in the following syntax:
2015-09-16T10:00:00
I need to take that string and make it a date object and have it be in the format MM/DD/YYYY hh:mm:ss and make sure its in the viewing users timezone automatically
I have the following function so far, but the issues I see are that
1.) I have to add the 'T' between the date and time in my string or firefox and IE9 tells me NaN and the date object I'm creating ISN'T A VALID DATE. (not sure why, but OK, I can live with adding the 'T')
2.) The bigger issue/problem: Firefox currently has this working and it shows the correct time for my time zone (10:00:00)... but in IE9, chrome and safari, it shows 6:00:00.
Question: How do I get the final output date string to ALWAYS be in the correct time (based on users time zone) across browsers without need of an external library?
Heres the function in its current state:
function cleanDateTime(thisdt) {
var d = new Date(thisdt) // CONVERT THE PASSED STRING TO A DATE OBJECT
var cleanedDate = '';
// GET ALL THE DATE PARTS...
var MM = (d.getMonth()+1).toString();
var DD = d.getDate().toString();
var YYYY = d.getFullYear().toString();
var hh = d.getHours().toString();
var mm = (d.getMinutes()<10?'0':'').toString() + d.getMinutes().toString();
var ss = (d.getSeconds()<10?'0':'').toString() + d.getSeconds().toString();
// BUILD THE FINAL DATE STRING FROM THOSE PARTS...
var cleanedDate = ( MM + '/' + DD + '/' + YYYY + ' ' + hh + ':' + mm + ':' + ss )
return cleanedDate;
};
and I call this function like so...
console.log ( cleanDateTime('2015-09-16T10:00:00') );
** UPDATE / PROBLEM SOLVED ( Thanks achan )...
As suggested, Im now using moment.js and I call the function like so to have it show correct time across browsers:
console.log ( cleanDateTime(moment("2015-09-16T10:00:00")) );
You will have to manually split the datestring and pass the individual parts of the date to the Date constructor and make any timezone adjustments in the process, again, manually. Or use moment.js as achan suggested in the comments.
var ds = '2015-09-16T10:00:00';
var dsSplit = ds.split('T');
var dateArr = dsSplit[0].split('-');
var timeArr = dsSplit[1].split(':');
var yr = dateArr[0], mon = dateArr[1], day = dateArr[2];
var hr = timeArr[0], min = timeArr[1], sec = timeArr[2];
var date = new Date(yr, mon, day, hr, min, sec);
There are a number of issues here. Firstly, never pass strings to the Date constructor because its parsing of strings is unreliable to day the least. The string "2015-09-16T10:00:00" is treated as follows:
In ECMA-262 ed 3 parsing is entirely implementation dependent, early versions of IE will not parse ISO 8601 format dates
In ES5, it will be treated as UTC
In ECMAScript 2015, it will be treated as local (which is also consistent with ISO 8601)
So unless you want to leave it to chance, always manually parse date strings.
Given that you can be sure that the string is a valid date, parsing it per ECMAScript 2015 only requires a couple of lines of code. The following functions create a Date based on either UTC or local time, depending on which you want. Of course it's pretty easy to make them one function with a toggle that looks for a trailing Z and uses UTC.
/** #param {string} s - date string in ISO 8601 format
** #returns {Date} - Date from parsing string as a local date time
**/
function parseISODateLocal(s) {
var b = s.split(/\D/);
return new Date(b[0], b[1]-1, b[2], b[3], b[4], b[5]);
}
document.write(parseISODateLocal('2015-09-16T10:00:00') + '<br>');
/** #param {string} s - date string in ISO 8601 format
** #returns {Date} - Date from parsing string as a UTC date time
**/
function parseISODateUTC(s) {
var b = s.split(/\D/);
return new Date(Date.UTC(b[0], b[1]-1, b[2], b[3], b[4], b[5]));
}
document.write(parseISODateUTC('2015-09-16T10:00:00'));
Presenting a date as 9/6/2015 10:00:00 on the web is likely to be very confusing for many since the vast majority of the world's population will expect the order to be day, month, year. Far better to use an unambiguous format using the month name like September 6, 2015 or 6-Sep-2015 or similar.
this is how i did mine...
var d, m, day, yr;
d = new Date();
day = d.getDate();
m = d.getMonth();
yr = d.getFullYear();
document.getElementById("dateObj").value = m + "/" + day + "/" + yr;
thanks for your vote..
momentjs.org
this is also my favorite javascript library (underscore)

How to create a date object from string in javascript [duplicate]

This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Closed 5 years ago.
Having this string 30/11/2011. I want to convert it to date object.
Do I need to use :
Date d = new Date(2011,11,30); /* months 1..12? */
or
Date d = new Date(2011,10,30); /* months 0..11? */
?
var d = new Date(2011,10,30);
as months are indexed from 0 in js.
You definitely want to use the second expression since months in JS are enumerated from 0.
Also you may use Date.parse method, but it uses different date format:
var timestamp = Date.parse("11/30/2011");
var dateObject = new Date(timestamp);
The syntax is as follows:
new Date(year, month [, day, hour, minute, second, millisecond ])
so
Date d = new Date(2011,10,30);
is correct; day, hour, minute, second, millisecond are optional.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
There are multiple methods of creating date as discussed above. I would not repeat same stuff. Here is small method to convert String to Date in Java Script if that is what you are looking for,
function compareDate(str1){
// str1 format should be dd/mm/yyyy. Separator can be anything e.g. / or -. It wont effect
var dt1 = parseInt(str1.substring(0,2));
var mon1 = parseInt(str1.substring(3,5));
var yr1 = parseInt(str1.substring(6,10));
var date1 = new Date(yr1, mon1-1, dt1);
return date1;
}
Very simple:
var dt=new Date("2011/11/30");
Date should be in ISO format yyyy/MM/dd.
First extract the string like this
var dateString = str.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
Then,
var d = new Date( dateString[3], dateString[2]-1, dateString[1] );
Always, for any issue regarding the JavaScript spec in practical, I will highly recommend the Mozilla Developer Network, and their JavaScript reference.
As it states in the topic of the Date object about the argument variant you use:
new Date(year, month, day [, hour, minute, second, millisecond ])
And about the months parameter:
month Integer value representing the month, beginning with 0 for January to 11 for December.
Clearly, then, you should use the month number 10 for November.
P.S.: The reason why I recommend the MDN is the correctness, good explanation of things, examples, and browser compatibility chart.
I can't believe javascript isn't more consistent with parsing dates. And I hear the default when there is no timezone is gonna change from UTC to local -- hope the web is prepared ;)
I prefer to let Javascript do the heavy lifting when it comes to parsing dates. However it would be nice to handle the local timezone issue fairly transparently. With both of these things in mind, here is a function to do it with the current status quo -- and when Javascript changes it will still work but then can be removed (with a little time for people to catch up with older browsers/nodejs of course).
function strToDate(dateStr)
{
var dateTry = new Date(dateStr);
if (!dateTry.getTime())
{
throw new Exception("Bad Date! dateStr: " + dateStr);
}
var tz = dateStr.trim().match(/(Z)|([+-](\d{2})\:?(\d{2}))$/);
if (!tz)
{
var newTzOffset = dateTry.getTimezoneOffset() / 60;
var newSignStr = (newTzOffset >= 0) ? '-' : '+';
var newTz = newSignStr + ('0' + Math.abs(newTzOffset)).slice(-2) + ':00';
dateStr = dateStr.trim() + newTz;
dateTry = new Date(dateStr);
if (!dateTry.getTime())
{
throw new Exception("Bad Date! dateStr: " + dateStr);
}
}
return dateTry;
}
We need a date object regardless; so createone. If there is a timezone, we are done. Otherwise, create a local timezone string using the +hh:mm format (more accepted than +hhmm).

Convert UNIX Time to mm/dd/yy hh:mm (24 hour) in JavaScript

I have been using
timeStamp = new Date(unixTime*1000);
document.write(timeStamp.toString());
And it will output for example:
Tue Jul 6 08:47:00 CDT 2010
//24 hour time
Screen real estate is prime, so I would like to take up less space with the date and output:
mm/dd/yy hh:mm
//also 24 hour time
Just add an extra method to the Date object, so you can reuse it as much as you want. First, we need to define a helper function, String.padLeft:
String.prototype.padLeft = function (length, character) {
return new Array(length - this.length + 1).join(character || ' ') + this;
};
After this, we define Date.toFormattedString:
Date.prototype.toFormattedString = function () {
return [String(this.getMonth()+1).padLeft(2, '0'),
String(this.getDate()).padLeft(2, '0'),
String(this.getFullYear()).substr(2, 2)].join("/") + " " +
[String(this.getHours()).padLeft(2, '0'),
String(this.getMinutes()).padLeft(2, '0')].join(":");
};
Now you can simply use this method like any other method of the Date object:
var timeStamp = new Date(unixTime*1000);
document.write(timeStamp.toFormattedString());
But please bear in mind that this kind of formatting can be confusing. E.g., when issuing
new Date().toFormattedString()
the function returns 07/06/10 22:05 at the moment. For me, this is more like June 7th than July 6th.
EDIT: This only works if the year can be represented using a four-digit number. After December 31st, 9999, this will malfunction and you'll have to adjust the code.

Categories