Format dates in Javascript - javascript

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]);

Related

getMonth throws wrong month (81) - Angular 6

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

Parsing date string and retrieving day with Javascript

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/

Javascript DateTime toString issues

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)"

Convert a string (in date format) to datetime using Javascript

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');

Javascript Date Object Issues With First Day of Month

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");

Categories