I've had a look through some of the suggestions in similar answers here but I can't find much that helps me.
Say I have a string that contains a date and a number: 2014-06-24 00:00:00
How would I parse it in a way that I can return this: 2014-06-24 00:00:00 Tuesday
Using date.parse as such:
new Date(Date.parse('2014-06-24 00:00:00'))
gives me the following result:
Tue Jun 24 2014 00:00:00 GMT+0100 (GMT Daylight Time)
Use methods getDay(),getDate() etc. to extract fields and format resulting string.
There are several JS sprintf implementations:
https://stackoverflow.com/a/3932473/2053898
https://github.com/alexei/sprintf.js
html
<div id="demo"></div>
js
//var a = new Date();
var a = new Date(Date.parse('2014-06-24 00:00:00'))
var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
year = a.getFullYear()
month = a.getMonth()
date = a.getDate()
hour = a.getHours()
minutes = a.getMinutes()
seconds = a.getSeconds()
day = a.getDay()
alert(year + "-" + month+ "-" + date + " " + hour + ":" + minutes + ":" + seconds + " " + days[a.getDay()])
document.getElementById("demo").innerHTML = year + "-" + month+ "-" + date + " " + hour + ":" + minutes + ":" + seconds + " " + days[a.getDay()]
you can check the demo here
http://jsfiddle.net/victor_007/7ohh7mjv/
http://momentjs.com is a great, powerful library for easy date manipulation. Worth using if you're doing a lot of it. To get 2014-06-24 00:00:00 Tuesday you could do (after linking in the library, of course).
var m = moment("2014-06-24T00:00:00");
var output = m.format('YYYY-MM-DD hh:mm:ss dddd');
But, really, check out the docs, because this is just the tip of the iceberg: http://momentjs.com/docs/#/parsing/string-format/
Related
I have a PHP script that records a timestamp in a Google Sheet. When I tried to see if this timestamp is between two other timestamps that I have entered manually into the same sheet, I discovered some odd behavior. I thought it might be because Google added a ' at the start of the string in the cell so I tried doing a substr to remove the apostrophe.
function weirdDate(dateFromPhp) {
var dateSubStr = new Date(dateFromPhp.substr(1));
var dateDefault = new Date(dateFromPhp);
return "dateFromPhp: " + dateFromPhp + " dateSubStr: " + dateSubStr + " dateDefault: " + dateDefault;
}
Output is:
dateFromPhp: 16/01/2020 08:33:45
dateSubStr: Mon Jun 01 2020 08:33:45 GMT+1000 (AEST)
dateDefault: Thu Apr 01 2021 08:33:45 GMT+1100 (AEDT)
I have no idea why these dates are months or years away from the expected and with different timezones. The operation without the substr resulted in the correct timezone for me.
Any idea how I can make this string into a timestamp with the correct date?
I discovered the answer. I had no idea javascript expected mm/dd/yyyy as the order for the date format.
function weirdDate(dateFromPhp) {
var dateSubStr = new Date(dateFromPhp.substr(1));
var dateDefault = new Date(dateFromPhp);
var dateUs = americanizeDate(dateFromPhp);
return "dateFromPhp: " + dateFromPhp + " dateSubStr: " + dateSubStr + " dateDefault: " + dateDefault + " dateUS: " + dateUs;
}
function americanizeDate(ausDate) {
var dateParts = ausDate.split("/");
// month is 0-based, that's why we need dataParts[1] - 1
var usDate = new Date(dateParts[1]+"/"+dateParts[0]+"/"+ dateParts[2]);
return usDate;
}
Switching the month and the day solved the problem.
I have to log my error with datetime in some file, for that I am using following code:
var dLogDate = new Date();
console.log(dLogDate.toString().substring(4) + ', ' + dLogDate.toGMTString().substring(4));
as per above code output comes as follows which is nice but not formated as I need:
"Oct 10 2014 12:48:59 GMT+0530 (IST), 10 Oct 2014 07:18:59 GMT"
I want result s follows :
"10 Oct 2014 12:48:59 (IST), 10 Oct 2014 07:18:59 (GMT)"
see date part before ",". I need 10 Oct instated of Oct 10
This can be done with some function which is substring first 4 character from string and concat at 3rd position again, But I am still curious to know if there are any other simple way to do this? I don't want to use any third party library/script.
Thanks.
You could try adding to the prototype an extension method toISTString
function pad(n) {
return (n < 10) ? '0' + n : n;
}
Date.prototype.toISTString = function(locale) {
var year = this.getFullYear().toString();
var month = this.toLocaleString(locale, { month: "short" }) // ECMAScript Internationalization API, which is very new only available in Blink browsers (Chrome and Opera), IE11, and Firefox 29+.
var day = this.getDate().toString();
var hrs = this.getHours().toString();
var mins = this.getMinutes().toString();
var secs = this.getSeconds().toString();
return day + " " + month + " " + year + " " + pad(hrs) + ":" + pad(mins) + ":" + secs + " (IST)";
};
dLogDate = new Date();
console.log(dLogDate.toISTString("en-us") + ', ' + dLogDate.toGMTString().substring(4));
JSFiddle
You can use date functions to format date
http://www.w3schools.com/jsref/jsref_obj_date.asp
var monthIndex = date.getMonth();
var dayIndex = date.getDay();
var monthArray = ['January',....];
var dayArray = ['Sunday',...]
console.log(monthArray[monthIndex] + "-" + dayArray[dayIndex]);
I'm trying to convert a Date to String with the following function:
Date.prototype.yyyymmdd = function () {
this.setHours(this.getHours() - 2);
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth() + 1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
var hh = this.getHours().toString();
var mm1 = this.getMinutes().toString();
return yyyy + '-' + (mm[1] ? mm : "0" + mm[0]) + '-' + (dd[1] ? dd : "0" + dd[0]) + ' ' + (hh[1] ? hh : "0" + hh[0]) + ':' + (mm1[1] ? mm1 : "0" + mm1[0]);
};
I use this line of code to test my convert method:
(value.lastConnectedAt == null ? emptyvalue : value.lastConnectedAt + " + " + new Date(value.lastConnectedAt).yyyymmdd())
I'm getting some really wierd results:
2014-06-23T08:43:42Z + 2014-43-23 08:43
The month is totally wrong, and the 2 hours arn't added. What am i doing wrong?
As for the explanation of your problem:
you get month = 43 instead of 06 because most probably you had a bug in a version that is different to the one posted where you had mm1 instead of mm[1] ; so you get month = minutes = 43
you get hours = 08 instead of your expected 06 most probably because your PC is on a timezone with UTC+02. getHours / setHours are expressed in local time. Use setUTCHours / getUTCHours instead
You don't need your own function, there's a javascript function that will convert date and time to string for you:
alert(new Date().toString())
output:
"Thu Aug 21 2014 12:20:38 GMT+0500 (Pakistan Standard Time)"
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Convert a date to string in Javascript
I have date in json format at client side :
/Date(1352745000000)/
The code which i have tried to parse Json date:
eval(dateTime.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));
and
new Date(parseInt(dateTime.substr(6)));
Out put I am getting:
Tue Nov 27 2012 00:00:00 GMT+0530 (India Standard Time)
Desire Output
2012-11-27 11:16
I am not able to figure out how we will get this.
var date = new Date(parseInt(dateTime.substr(6)));
var formatted = date.getFullYear() + "-" +
("0" + (date.getMonth() + 1)).slice(-2) + "-" +
("0" + date.getDate()).slice(-2) + " " + date.getHours() + ":" +
date.getMinutes();
Best not to try save space with this one :)
var str, year, month, day, hour, minute, d, finalDate;
str = "/Date(1352745000000)/".replace(/\D/g, "");
d = new Date( parseInt( str ) );
year = d.getFullYear();
month = pad( d.getMonth() + 1 );
day = pad( d.getDate() );
hour = pad( d.getHours() );
minutes = pad( d.getMinutes() );
finalDate = year + "-" + month + "-" + day + " " + hour + ":" + minutes;
function pad( num ) {
num = "0" + num;
return num.slice( -2 );
}
The output you are getting is not string - you are getting string representation of Date object.
You need to format it in proper way before further processing. To see how to do that, just see this answer: https://stackoverflow.com/a/8398929/548696
To add time to the date, see documentation on Date JS object: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
I'm working with Javascript dates, and I'm getting a bit confused with trying to take a date from a string.
This is the code I have:
var formatDate = function(dateObj) {
// make sure date values are two digits and months start at 1
var adjMonth = dateObj.getMonth() + 1;
var adjDate = dateObj.getDate();
if (adjMonth < 10) adjMonth = '0' + adjMonth;
if (adjDate < 10) adjDate = '0' + adjDate;
// build and return dateStr
var dateStr = dateObj.getFullYear() + '-' + adjMonth + '-' + adjDate;
return dateStr;
};
$(document).ready(function() {
var testIn1 = "2012-02-01";
var testDate1 = new Date(testIn1);
var testDate1Str = formatDate(testDate1);
var testIn2 = "2012-01-31";
var testDate2 = new Date(testIn2);
var testDate2Str = formatDate(testDate2);
$('#output').html("---Input = '" + testIn1 + "':<br>" + testDate1 + "<br>" + testDate1Str + "<br>"
+"---Input = '" + testIn2 + "':<br>" + testDate2 + "<br>" + testDate2Str + "<br>");
});
Results I get from this are:
---Input = '2012-02-01':
Tue Jan 31 2012 18:00:00 GMT-0600 (CST)
2012-01-31
---Input = '2012-01-31':
Mon Jan 30 2012 18:00:00 GMT-0600 (CST)
2012-01-30
Which makes no sense to me, why are the days one off? Doesn't seem sensical to get 2012-01-31 from 2012-02-01... What am I missing here?
It looks like Date.parse uses 00:00:00 GMT if you don't pass a time, and it will be 18:00:00 the previous day in your time zone (GMT-6). If you do pass an explicit time, then this behaviour is suppressed:
Date.parse(testIn1 + " 00:00:00");