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)"
Related
I use this function in my Javascript code in order to format dateTime object into string and this function works fine for Firefox and Chrome but not for IE and Safari.
Does anyone know what to do in order to make this also work with Safari and IE?
date Object looks like this in Chrome: Mon Mar 25 2019 00:00:00 GMT+0100 (CET)
function formatDateTimeToString(date) {
var dd = (date.getDate() < 10 ? '0' : '') + date.getDate();
var MM = ((date.getMonth() + 1) < 10 ? '0' : '') + (date.getMonth() + 1);
var yyyy = date.getFullYear();
var hours = (date.getHours() < 10 ? '0' : '') + date.getHours();
var minutes = (date.getMinutes() < 10 ? '0' : '') + date.getMinutes();
return (dd + "." + MM + "." + yyyy + ' ' + hours + ':' + minutes);
}
console.log(formatDateTimeToString(new Date()));
If the date object for Safari is generated the same way as it is done for Chrome, then at least in my old version of Safari the code runs successfully, as follows:
function formatDateTimeToString(date) {
var dd = (date.getDate() < 10 ? '0' : '') + date.getDate();
var MM = ((date.getMonth() + 1) < 10 ? '0' : '') + (date.getMonth() + 1);
var yyyy = date.getFullYear();
var hours = (date.getHours() < 10 ? '0' : '') + date.getHours();
var minutes = (date.getMinutes() < 10 ? '0' : '') + date.getMinutes();
return (dd + "." + MM + "." + yyyy + ' ' + hours + ':' + minutes);
}
var d = document;
d.w = d.writeln;
var date = new Date("Mon Mar 25 2019 00:00:00 GMT+0100 (CET)");
/* this works */
d.w( formatDateTimeToString(date)+"<BR>");
// output:
// 24.03.2019 16:00
You may get NaN as a result in Safari if you attempt to instantiate a Date object with a string containing hyphens, as follows:
var d = document;
d.w = d.writeln;
date = new Date("2019-03-24");
/* returns NaN */
d.w( formatDateTimeToString(date)+"<BR>");
date = new Date("03-24-2019");
/* this fails with NaN*/
d.w( formatDateTimeToString(date)+"<BR>");
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 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 have the follow function that properly returns the date in the format required, but the value returned isn't respecting the local timezone. In this case, its 4 hours off. What would I need to modify in this function to make it add the proper offsets based on the users location?
Thanks!
function date_str(seconds) {
var dt = new Date(1970, 0, 1);
dt.setSeconds(seconds);
console.log(dt);
var month = dt.getMonth() + 1;
var date = dt.getDate();
var year = dt.getFullYear();
var hours = dt.getHours();
var minutes = dt.getMinutes();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes < 10 ? '0' + minutes : minutes;
return month + '/' + date + '/' + year + ', ' + hours + ':' + minutes + ' ' + ampm;
}
Edit: Passing unix time to function 1396450616.505 which converts to Wed, 02 Apr 2014 14:56:56 GMT which returns Sent at 4/2/2014, 2:56 PM from the function itself. The time here is 10:56 AM EST.
Assuming that seconds is a unix epoch (UTC), you should just use
function date_str(seconds) {
var dt = new Date(seconds*1000);
console.log(dt);
…
instead. The get…() methods will respect the local timezone. If you don't want that, you should use the getUTC…() equivalents.
In BIRT, i have a column containing a datetime stored as a string. I need to convert these string to datetime format and put the result in another column using Javascript.
The string is the form of: for example: Fri 21 Feb 2014, 09:40 AM.
Hence this when converted to a datetime format and exported to excel, the column should be treat as a date.
Can any one of you help me to do it?
Cheers,
Other answers do not take into consideration this question is in a BIRT context.
Create a computed column in your dataset, with "Date time" as datatype
Enter as expression:
new Date(row["myDateStringField"]);
Where "myDateStringField" is your DateTime column in a String format. Then use this computed column in your report instead of the String column.
That's it!
Checkout momentjs!
You can parse your time of any format like
moment("12-25-1995", "MM-DD-YYYY");
In your case, you don't even have to specify the format. It automatically recognizes it.
And you can output ISO format or convert it to a Javascript Date object.
This is extremely easy to do with javascript. The following code will make a date in a format that Excel will recognize as a date.
http://jsfiddle.net/bbankes/d7SwQ/
var dateString = 'Fri 21 Feb 2014, 09:40 AM';
var date = new Date(dateString);
var yr = date.getFullYear();
var mo = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var hr = hours < 10 ? '0' + hours : hours;
var minutes = date.getMinutes();
var min = (minutes < 10) ? '0' + minutes : minutes;
var seconds = date.getSeconds();
var sec = (seconds < 10) ? '0' + seconds : seconds;
var newDateString = yr + '-' + mo + '-' + day;
var newTimeString = hr + ':' + min + ':' + sec;
var excelDateString = newDateString + ' ' + newTimeString;
If you just want to reformat 'Fri 21 Feb 2014, 09:04 AM' as '2014-02-21 09:04', then the following will do:
function stringToTimestamp(s) {
var t = s.match(/[\d\w]+/g);
var months = {jan:'01',feb:'02',mar:'03',apr:'04',may:'05',jun:'06',
jul:'07',aug:'08',sep:'09',oct:'10',nov:'11',dec:'12'};
function pad(n){return (n<10?'0':'') + +n;}
var hrs = t[4] % 12;
hrs += /pm$/i.test(t[6])? 12 : 0;
return t[3] + '-' + months[t[2].toLowerCase()] + '-' + pad(t[1]) + ' ' +
pad(hrs) + ':' + pad(t[5]);
}
console.log(stringToTimestamp('Fri 21 Feb 2014, 09:04 AM')); // 2014-02-21 09:04
use the ISO format: YYYY-MM-DDTHH:MM:SS or YYYY-MM-DD
new Date('2011-04-11T11:51:00');
or
new Date('2011-04-11');