I've a requirement where I have to show the Date timestamp in following format.
MM:DD:YYYY HH:MM:SS IST/CST/CDT.
I have used javascript date object to get the date and time. But I don't know how to get the timezone (IST or CST or CDT or etc) from the obj. Do we have any technique or native javascript Plugin (non-jQuery plugin) to get this timezone abbreviated value?
Check out moment.js library and its format method, with which you can format a date to include the time zone.
Below is pure JS code, without using any third party library
var x = new Date();
var tz = x.toTimeString().match(/\((.+)\)/)[1];
var month = x.getMonth() + 1;
month = month < 10 ? ('0' + month) : month.toString();
var date = x.getDate() < 10 ? ('0' + x.getDate()) : x.getDate().toString();
var hour = x.getHours() < 10 ? ('0' + x.getHours()) : x.getHours().toString();
var min = x.getMinutes() < 10 ? ('0' + x.getMinutes()) : x.getMinutes().toString();
var sec = x. getSeconds() < 10 ? ('0' + x.getSeconds()) : x.getSeconds().toString();
var output = month + ':' + date + ':' + x.getFullYear() + ' ' + hour + ':' + min + ':' + sec + ' ' + tz
Related
So we have multiple clients, that are in multiple time zones. I'm pulling some dates from an API, and the dates/times that are in this string are exactly what I need to display. I've been researching this, and digging for some time, and still haven't come up with a clear answer. The string coming in is formatted as such:
"2017-12-29T20:00:00"
What I'm wanting is to extract both the date and time as is, into two strings (no timezone offsetting, no matter where the viewer is located) but am having some issues doing so. Also hoping to format it in the correct fashion as well. Example:
"M/d/yyyy"
"hh:mm AM/PM" (12 hour)
I've tried numerous ways to battle this, and don't really want to just grab substrings, but am half tempted to do so. Any help is appreciated.
Consider just reformatting the string, it avoids all issues with the built-in parser and timezones:
function reformatTimestamp(s) {
function z(n){return (n<10?'0':'')+ +n}
var b = s.split(/\D/);
var h = b[3]%12 || 12;
var ap = b[3] < 12? 'AM':'PM';
return b[1] + '/' + b[2] + '/' + b[0] +
' ' + z(h) + ':' + z(b[4]) + ' ' + ap;
}
console.log(reformatTimestamp('2017-12-29T20:00:00')) // 12/29/2017 08:00 PM
I think it would be better to pad the month and day with a leading zero (but I'd also use an unambiguous date format like DD-MMM-YYYY rather than the peculiar m/d/y).
Use this code:
function formatAMPM(date) {
var hours = date.getUTCHours();
var minutes = date.getUTCMinutes();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
var str = "2017-12-29T20:00:00";
var dt = new Date(str + "Z");
console.log("M/d/yyyy");
console.log((dt.getUTCMonth() + 1) + '/' + dt.getUTCDate() + '/' + dt.getUTCFullYear());
console.log("hh:mm AM/PM");
console.log(formatAMPM(dt));
var options = {timeZone:'Asia/Tokyo'};
var date = new Date(1502722800000);
date.toString('YYYYMMDD HH:MM');
console.log('formatted date '+date);
o/p - Mon Aug 14 2017 20:30:00 GMT+0530 (IST)
But I want o/p in this date format('YYYYMMDD HH:MM') as 20170814 17:30
toString() does not accept any arguments, and cannot be used like this. I would recommend using moment.js.
For example:
var formatted = moment(1502722800000).format('YYYY/MM/DD h:mm');
console.log('formatted date '+formatted);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
If you wish to work with timezones, you can also add Moment Timezones.
The question was about a solution in JavaScript for a specific format, so without any additional libraries, a straight forward answer would be (in the style of the shim for Date.toISOString):
function pad(number) {
if (number < 10) {
return '0' + number;
}
return number;
}
function toMyDateFormat(s) {
return this.getUTCFullYear() +
pad(this.getUTCMonth() + 1) +
pad(this.getUTCDate()) +
' ' + pad(this.getUTCHours()) +
':' + pad(this.getUTCMinutes());
};
Just for curiosity, this is my shortest solution without any library:
function toMyDateFormat(d) {
return d.toISOString().replace(/-/g,'').replace('T', ' ').substr(0,14);
}
SurisDziugas is right, with moment, you can just create and format your date like this moment(1502722800000).format('YYYYMMDD HH:MM');
I actually stopped using JS native Date object, moment offers better possibilities.
Without using any library, this can be your long solution.
function formatDate(date) {
var month = '' + (date.getMonth() + 1),
day = '' + date.getDate(),
year = "" + date.getFullYear(),
hour = "" + date.getHours(),
min = "" + date.getMinutes();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
if (hour.length < 2) hour = '0' + hour;
if (min.length < 2) min = '0' + min;
return year+"/" + month +"/"+ day + " " + hour + ":" + min;
}
var options = {
timeZone: 'Asia/Tokyo'
};
var date = new Date(1502722800000);
console.log(formatDate(date));
I hope this helps
How can I get the date and time in javascript as 12/08/2015-1:49? I tried the following but I get an error TypeError: now.format is not a function
var now = new Date();
now.format("dd/mm/yy-h:mm tt");
console.log(now); //TypeError: now.format is not a function
There is no any format method for Date in JavaScript. Either you need to use any other external libraries like momentjs, or write your own script to format.
Here is example how you can convert date to dd/mm/yy-h:mm tt format
var now = new Date();
var date = now.getDate() + "/" + (now.getMonth() + 1) + "/" + now.getFullYear() + "-" + now.getHours() + ":" + now.getMinutes() + " " + (now.getHours() > 12 ? "PM" : "AM");
console.log(date)
Try this:
function getFormattedDate() {
var date = new Date();
var str = date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getYear() + "-" + date.getHours() + ":" + date.getMinutes() + " " + date.getSeconds();
return str;
}
Extend Date`s prototype, add function format
Date.prototype.format = function(format){
format = format || "Y/M/D H:I:S";
var data = {
y: this.getFullYear() % 100,
Y: this.getFullYear(),
m: this.getMonth() + 1,
d: this.getDate(),
h: this.getHours(),
i: this.getMinutes(),
s: this.getSeconds()
};
var needAddZeroLTTen = "mdhis".split('');
for(var i = 0; i < needAddZeroLTTen.length; i ++){
var prop = needAddZeroLTTen[i];
data[prop.toUpperCase()] = data[prop] < 10 ? ('0' + data[prop]) : data[prop];
}
var dateStr = format;
for(var i in data){
var reg = new RegExp(i,'g');
dateStr = dateStr.replace(reg, data[i]);
}
return dateStr;
}
Then use below code to format a date
var date = new Date();
var dateStr = date.format('D/M/y-h:I');
the best way to manage dates in js is using http://momentjs.com/ here you will find a great way to format the dates
You can either
do this by hand by using the functions on Date like date.getMonth(), however these do not support zero padding, and it gets quite fiddly. Only do this if you cannot include a third-party library, you're obsessive about load time / performance or you really enjoy re-inventing the wheel.
Use a third-party library like moment, this has multiple formats and supports padding, e.g. MM will force month as two characters.
Example
var now = new Date();
console.log(moment(now).format("DD/MM/YY-hh:mm Z"));
Moment.JS would help you.
Please take a look on this JSFiddle: http://jsfiddle.net/f3zp5zuv/
alert (moment('2015 Apr 30').format('DD/MM/YY -h:mm'))
Moment: http://momentjs.com/docs/#/displaying/
alert (moment('2015 Apr 30 14:42:00').format('DD/MM/YY -h:mm'))
<script src="http://momentjs.com/downloads/moment.js"></script>
I have a grid in which each row has a PHP format('Y-m-d H:i:s') date displayed.I wanted to apply a javascript filter which will show only those rows which has timestamp past 36hrs.
Whats the best way to first get past 36hrs timestamp & then compare that timestamp with displayed PHP timestamp using javascript.
Till now I tried using below code to get past 36 timestamp
var mydate=new Date();
mydate.setHours(mydate.getHours()-36);
dateInPhpFormat=mydate.getFullYear()+'-'+mydate.getMonth()+'- '+mydate.getDate()+"
"+mydate.getHours()+":"+mydate.getMinutes()+":"+mydate.getSeconds();
When I print dateInPhpFormat it shows wrong date.
Any help would be appreciated .
The only thing that could be wrong is that Javascript gives you the month, day, minues and seconds without leading zero. Also months are zero based, so you need to add 1 to the month.
For example month In JS: 3, in PHP(with 'm'): 03
You can add this leading zero yourself, like this;
var mydate=new Date();
mydate.setHours(mydate.getHours()-36);
var month = ('0' + (mydate.getMonth() + 1)).substr(-2);
var day = ('0' + mydate.getDate()).substr(-2);
var hour = ('0' + mydate.getHours()).substr(-2);
var minute = ('0' + mydate.getMinutes()).substr(-2);
var second = ('0' + mydate.getSeconds()).substr(-2);
dateInPhpFormat = mydate.getFullYear() + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
This will give you a date string which is identical to php date('Y-m-d H:i:s')
JavaScript Date objects use zero based months for some reason. Try adding 1 to the month.
dateInPhpFormat = mydate.getFullYear() + '-' + (mydate.getMonth() + 1 ) +'-'+mydate.getDate() + " " + mydate.getHours() + ":" + mydate.getMinutes() + ":" + mydate.getSeconds();
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');