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");
Related
I am trying to get the month of a date, but it keeps showing me this: "2018-81-26 07:00".. This is my function that I use for setting the date that I need:
selectStartTime(time) {
this.selectedTime = '' + time.time + ' ' + time.period;
var date = new Date(this.start_at); // this shows good date:
//Wed Sep 26 2018 00:00:00 GMT+0200 (Central European Summer Time)
var period = time.period;
var hours = '';
// error occurs here:
var year = date.getFullYear() + '-' + date.getMonth()+1 + '-' + date.getDate();
// year: 2018-81-26 07:00
if (period === 'PM') {
hours = '' + (time.value + 12) + ':00';
this.campaignModel.starts_at = year + ' ' + hours;
} else {
hours = time.time;
this.campaignModel.starts_at = year + ' ' + hours;
}
}
What am I doing wrong?
just change below code
var year = date.getFullYear() + '-' + (date.getMonth()+1) + '-' + date.getDate();
It's actually because of the +1
var year = date.getFullYear() + '-' + date.getMonth()+1 + '-' + date.getDate();
It gets date.getMonth which is equal to 8, but since you're doing +1 and the var is treated as a string, instead of adding one, it adds the number 1 at the end, which makes it 81
If for whatever reason you need the +1, you should declare it before hand like
var month = year.getMonth() + 1;
var year = date.getFullYear() + '-' + month+ '-' + date.getDate();
Or do like other answers did correctly as well
var year = date.getFullYear() + '-' + (date.getMonth()+1) + '-' + date.getDate();
Try this.
var year = date.getFullYear() + '-' + (date.getMonth()+1) + '-' + date.getDate();
I would recommend you to use a popular library for handling/dealing with date and time
https://momentjs.com/
var d = moment(scope.date);
d.month(); // 1
d.format('ddd MMM DD YYYY'); // 'Mon Feb 01 2016
today im using Momentjs its better for many purposes
https://momentjs.com/
you can format dates and retrieve any part of that like this
moment().format('MMMM Do YYYY, h:mm:ss a'); // September 25th 2018, 10:02:25 am
moment().format('dddd'); // Tuesday
moment().format("MMM Do YY"); // Sep 25th 18
moment().format('YYYY [escaped] YYYY'); // 2018 escaped 2018
moment().format(); // 2018-09-25T10:02:48-03:00
I have a date in format YYYYMMDDTHHMMSS and need to get the date in format DD.MM.YYYY HH:MM:SS .
I do such:
var dateTimeFormat;
var dateAsString = dataTimeFormat.split('', dateTimeFormat.lenght);
var year = dateAsString.splice(0, 4).join('');
var month = dateAsString.splice(0, 2).join('');
var day = dateAsString.splice(0, 2).join('');
var hours = dateAsString.splice(1, 2).join('');
var minutes = dateAsString.splice(1, 2).join('');
var seconds = dateAsString.splice(1, 2).join('');
var date = day + '.' + month + '.' + year + ' ' + hours + ':' + minutes + ':' + seconds;
return date;
But how can I convert date to Date format?
After transforming string into a known format, Date::parse() will be enough:
var yourDate = new Date(Date.parse(date));
WORKING DEMO:
var date = "2016.06.15 10:10:10";
var yourDate = new Date(Date.parse(date));
alert(yourDate);
NOTE: your format is a bit weird, but maybe parse will accept it as long as it accept many string formats such as:
Date.parse("Aug 9, 1995");
Date.parse("Wed, 09 Aug 1995 00:00:00");
Date.parse("Wed, 09 Aug 1995 00:00:00 GMT");
i think this is easy way to do this =). hope it help
<script>
dateTimeFormat = '20161506T112130';
str = dateTimeFormat.split("");
date = str[0] + str[1] + str[2] + str[3] + '.' + str[4] + str[5] + '.' + str[6] + str[7] + ' ' + str[9] + str[10] + ':' + str[11] + str[12] + ':' + str[13] + str[14];
console.log(date);
</script>
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'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/
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)"