I'm trying to implement a parser for the tablesorter plugin for jQuery and I have this strange behaviour with the getTime() value for dates. The following code:
var dateOne = '03/04/2010';
var dateTwo = '28/10/2008';
var dateOneTime = new Date(dateOne).getTime();
var dateTwoTime = new Date(dateTwo).getTime();
var diff = dateOneTime - dateTwoTime;
alert('dateOneTime: ' + dateOneTime + '\ndateOne: ' + dateOne + '\nDateTwoTime: ' + dateTwoTime + '\ndateTwo : ' + dateTwo + '\none - two: ' + diff);
Gives a getTime() result for the 2010 date as 1267 billion or so, and for the 2008 date 1271 billion. Therefore subtracting dateTwo from dateOne gives a negative number. Why is this? Surely the dateTwo value, being in 2008, should be smaller?
Date expects MM/DD/YYYY
You are passing in DD/MM/YYYY
By default, the format is mm/dd/yyyy. Thus, 28/10/2008 is being interpreted as 04/10/2010.
When you initialize a date in JS via a string, it should be an RFC1123-compliant format - yours aren't.
new Date(dateTwo) is being interpreted incorrectly as April 10 2010 because the Date constructor is expecting MM/DD/YYYY instead of the DD/MM/YYYY you are passing.
try
var dateOne = '04/03/2010';
var dateTwo = '10/28/2008';
Related
i needed to convert string to UTC date , and then UTC date to local date.
here is my code :
var dateStr = "9/8/2015 12:44:00 PM";
console.log(strtoUTCtoLocal(dateStr));
function strtoUTCtoLocal(dateStr)
{
var d1 = new Date(dateStr).toUTCString();
var d2= new Date(d1);
return "0" + (d2.getMonth()+1).toString().slice(-2) + "/" +
"0" + d2.getDate().toString().slice(-2) + "/" +
d2.getFullYear().toString() + " " +
d2.getHours().toString() + ":" +
d2.getMinutes().toString();
}
Parsing date strings should be done manually since Date.parse is inconsistent across browsers. Assuming your format is d/m/y, you can parse it to a UTC time using the following:
var s = '9/8/2015 12:44:00 PM';
function parseDate(s) {
var b = s.split(/\D+/);
var ap = /pm$/i.test(s)? 12 : 0;
return new Date(Date.UTC(b[2], b[1]-1, b[0], ((b[3]%12) + ap), b[4], b[5]));
}
document.write(parseDate(s));
If you need to validate the date, you'll need an extra line of code.
Note that by default, strings without a timezone are generally parsed as local (except for ISO 8601 format strings in ES5 using Date.parse, but ECMAScript 2015 parses them as local, which was changed to UTC with ECMAScript 2016).
I'd recommend checking out momentjs (http://momentjs.com/). It's an awesome library that handles all sorts of date operations like this.
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)
I have a string 10/11/2012 meaning November 10, 2012.
But when I do new Date("10/11/2012") it returns October 11th.
How do I pass in the date format I want? In this case dd-mm-yyyy
I found jQuery.datepicker.parseDate(format, Date) at this site:
http://docs.jquery.com/UI/Datepicker/$.datepicker.parseDate
So I will be using the jQuery datepicker instead.
Unfortunately, there's no JavaScript Date constructor that allows you to pass in culture information so that it uses localized date formats. Your best bet is to use the constructor that takes the year, month, and day separately:
var parts = dateString.split('/');
var date = new Date(parseInt(parts[2], 10),
parseInt(parts[1], 10),
parseInt(parts[0], 10));
For this specific case, you can use:
var dateparts = date.split("/");
var datestring = dateparts[1] + "/" + dateparts[0] + "/" + dateparts[2];
var date = new Date(datestring);
In the more general case, you can extend the Date prototype, as demonstrated in this answer:
https://stackoverflow.com/a/13163314/1726343
I wondering what is the best way to convert a timestamp of this format -
2012-02-18 14:28:32
to a date presentation of this format -
Saturday Feb 2012 14:28:32
Many thanks :)
Javascript date functions are pretty bad... You have the option to convert to UTC http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_toutcstring
But if it was me, i would look into Datejs: http://www.datejs.com/ best javascript date api for me
Please take a look at the getting started with Datejs: http://www.datejs.com/2007/11/27/getting-started-with-datejs/
You must first define an array of the English words (Sunday, Monday, Feb, Mar, etc.):
var daysOfWeek = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],
monthsOfYear = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
To be able insert the extra 0 at the beginning of the minutes and seconds, define a padding function for the String prototype:
String.prototype.padLeft = function(padString,length){
var toReturn = String(this);
while(toReturn.length < length){
toReturn = padString + toReturn;
}
return toReturn;
}
Format the date and time like this:
var time = new Date(), formattedDate, formattedTime, wholeThing;
formattedDate = daysOfWeek[time.getDay()] + ", " + monthsOfYear[time.getMonth()] + " " + time.getDate() + ", " + time.getFullYear();
formattedTime = time.getHours() + ":" + time.getMinutes().padLeft("0",2) + time.getSeconds().padLeft("0",2);
You can get the whole thing by concatenating formattedDate and formattedTime, as in:
wholeThing = formattedDate + " " + formattedTime;
Consider using datejs which is rocks!
var mydate = Date.parse('2012-02-18 14:28:32');
var result = mydate.toString('dddd MMM yyyy h:mm:ss');
console.log(result);
I'd suggest using an external js library to do that. To my understanding, Moment.js is the best date-time conversion library out there.
In this case, it does the job in one line. Just add the moment.js in you project and then do
var timestamp = '2012-02-18 14:28:32';
var formattedTime = moment(timestamp).format('dddd MMM YYYY HH:mm:ss'); // Saturday Feb 2012 14:28:32
JavaScripts Date object is lacking methods for formatting. I would consider using an external library like this one. Seems it has what you're looking for.
try this blog it has enough dateformats:
http://blog.stevenlevithan.com/archives/date-time-format
I am getting Facebook users' friends birthday back from Facebook in the following format:
10/07/1967 or just the day and month as 10/07
I want to display it as "October, 07, 1967" or "October, 07"
Is there a way to convert this string into a date and format it in Javascript?
var MONTHS = ["January","February","March","April","May","June","July","August","September","October","November","December"];
var myDate, myFormatDate;
var date_str ='10/07/1967';
var t = date_str.split("/");
if(t[2]) {
myDate = new Date(t[2], t[0] - 1, t[1]);
myFormatDate = MONTHS[myDate.getMonth()] + "," + myDate.getDate() + "," + myDate.getFullYear();
} else {
myDate = new Date(new Date().getFullYear(), t[0] - 1, t[1]);
myFormatDate = MONTHS[myDate.getMonth()] + "," + mydate.getDate();
}
= RESULT:
= myDate -- the Date Object
= myFormatDate -- formated date string "October, 07, 1967"
Check out the awesome DateJS library. You'll be able to do what you want, and more ...
[No, i'm not involved in any way with DateJs, just a very satisfied user :-)]
To do it fast, without bells and whistles, you can first split your date
myDateParts = myDate.split("/");
Then build the new date from the parts:
myNewDate = new Date(myDateParts[2], myDateParts[1], myDateParts[0]);
Using moment.js you can convert a date with:
moment('10/07/1967', "MM/DD/YYYY").format("MMMM, DD, YY")
where the first part get a date from a string given a format ("MM/DD/YYYY"), then you just format the date as you wish giving another format ("MMMM, DD, YY")
If you don't want to use a framework, you could just pass in the string to the date constructor:
var birthday = new Date('10/07/1967');
The constructor will also accept strings without year, like '10/07'.
Then you can access each of the properties as you wish:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date