Format Date Time in Javascript [duplicate] - javascript

This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 5 years ago.
I should format my datetime value in javascript to this format yyyy-MM-dd hh:mm:ss
I tried this
var btf = new Date(value.createDate);
var billingTimeFormatted = btf.getFullYear() + "-" + btf.getMonth() + "-" + btf.getDate() + " " + btf.getHours() + ":" + btf.getMinutes() + ":" + btf.getSeconds();
But it result to this
2017-8-31 02:00:00
month and date should be 2-digit (08 intead of 8)
What could be the best workaround?
*type on minutes is edited

Nothing wrong with your code. Javascript returns the integer < 10 in single digit only. Format it to string of 2 with a function.
function formatWithZero(val)
{
// as per comment by #RobG below, return ('0'+val).slice(-2) will also
// do the same thing in lesser lines of code. It works and can be used.
var value = val.toString();
if(value.length > 1)
return value;
var str = "00"+value;
return str.slice(str.length-2,str.length); ;
}
//I am using Date.now(), you can use your value.
var btf = new Date(Date.now());
var billingTimeFormatted = btf.getFullYear() + "-" + formatWithZero(btf.getMonth()) + "-" + formatWithZero(btf.getDate()) + " " + formatWithZero(btf.getHours()) + ":" + formatWithZero(btf.getMinutes()) + ":" + formatWithZero(btf.getSeconds());
alert(billingTimeFormatted);

You forgot () for getMinutes(), to have 2 digits :
var btf = new Date();
var currentMonth = btf.getMonth();
if (currentMonth < 10) { currentMonth = '0' + currentMonth; }
var billingTimeFormatted = btf.getFullYear() + "-" + currentMonth + "-" + btf.getDate() + " " + btf.getHours() + ":" + btf.getMinutes() + ":" + btf.getSeconds();

Related

Getting the date from Javascript comes up with bizarre values

I want to get the date and time in the following format:
yyyy.mm.dd.hh.mm.ss | 2014.11.6.20.31.24
However, my code (based on Get Current Time) is instead providing these values:
y??.m?.d?.hh.mm.ss | 114.10.4.20.31.24
Here is my code:
var dt = new Date();
var time = dt.getHours() + "." + dt.getMinutes() + "." + dt.getSeconds();
var date = dt.getYear() + "." + dt.getMonth() + "." + dt.getDay();
alert(date + "." + time);
Can someone please let me know why these odd values are in there 114.10.4 and how to change them to be what I want?
That is because you need to use
.getFullYear() for the full year
the .getMonth() is 0-based so you need to add 1
the function to get the day of month is .getDate(). The .getDay() is for the day of the week.
var dt = new Date();
var time = dt.getHours() + "." + dt.getMinutes() + "." + dt.getSeconds();
var date = dt.getFullYear() + "." + (dt.getMonth()+1) + "." + dt.getDate();
alert(date + "." + time);
If, for some weird reason, you are going only for firefox, you can use
var d = new Date(),
formatted = d.toLocaleFormat('%Y.%m.%d.%H.%M.%S');
alert(formatted);
Finally, you can use the great moment.js library and do
var formatted = moment().format('YYYY.MM.DD.HH.mm.ss');
You are using the wrong getters. Use getFullYear() instead of getYear(), and getDate() instead of getDay(). And add 1 to the month, because it starts at 0.
var dt = new Date();
var time = dt.getHours() + "." + dt.getMinutes() + "." + dt.getSeconds();
var date = dt.getFullYear() + "." + (dt.getMonth() + 1) + "." + dt.getDate();
alert(date + "." + time);
Just make sure that you are using methods what you want to use e.g:
dt.getYear() => dt.getFullYear()
For further reference see this.
should use getFullYear() instead of getYear() and getMonth() + 1 instead of getMonth() because it calculate form 0..11 and info about getDay()
var dt = new Date();
var time = dt.getHours() + "." + dt.getMinutes() + "." + dt.getSeconds();
var date = dt.getFullYear() + "." + dt.getMonth() + 1 + "." + dt.getDate();
alert(date + "." + time);
dt.getDay() this day of the week
The getDay() method returns the day of the week (from 0 to 6)
You need to use getDate() to know the number of the day (from 1 to 31)
Also, you need to add 1 to getMonth() because months in JavaScript starts on 0

how to change the date format using jquery

I have a input date field whose value is in this "2014-06-07 07:14"(year-month-date hour:minute) format how can i change it to 06/07/2014 07/14( mm/dd/yy) format using jquery.
DateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.ENGLISH);
DateFormat targetFormat = new SimpleDateFormat("dd/MM/yyyt hh/mm");
Date date = originalFormat.parse("2014-06-07 07:14");
String formattedDate = targetFormat.format(date); // 06/07/2014 07/14
Docs of SimpleDateFormat#format
PS: A JavaScript implementation of the format() method of Java's SimpleDateFormat: is available here
Why using jQuery to do this ?
Use plain js:
var date = new Date('2014-06-07 07:14');
alert((date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear() + ' ' + date.getHours() + '/' + date.getMinutes());
http://jsfiddle.net/F4nq8/
It seems that IE and Safari have some bug with YYYYMMDD dates so a workaround could be something like:
var s = "2014-06-07 07:14";
var t = s.split(" ");
var d = t[0].split("-");
var x = d[1] + "/" + d[2] + "/" + d[0] + " " + t[1];
var date = new Date(x);
alert((date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear() + ' ' + date.getHours() + '/' + date.getMinutes());
http://jsfiddle.net/F4nq8/4/
Some reference about this behaviour: http://biostall.com/javascript-new-date-returning-nan-in-ie-or-invalid-date-in-safari

How to parse Date from JSON

I am using a grid view which is getting bind by json also on some conditions and a coloum of grid contains date , so while getting data from json, I need to parse the date. I am able to get date but not time part . Tried and searched too much . I am mentioning below two methods that I tried but not solves my problem.
{
function ParseDate(jsonDate) {
date = new Date(parseInt(String(jsonDate).substr(6)));
day = date.getDate();
month = date.getMonth() + 1;
year = date.getFullYear();
return month + "/" + day + "/" + year;
}
}
This gives me only date but I need time, so I did one more method
{
function ParseDate(jsonDate) {
var date = new Date(parseInt(jsonDate.substr(6)));
var formatted = ("0" + (date.getMonth() + 1)).slice(-2) + "/" + ("0" + date.getDate()).slice(-2) + "/" + date.getFullYear() + " " + date.getHours() + ":" + date.getMinutes() + ":" + "0" + date.getSeconds();
return formatted;
}
}
but this function returns
//07/19/2013 11:38
instead of //7/19/2013 11:38:07 AM which is desired result.Please help me solving this problem. Thank You very much. Also , I need to show Am or PM that is compulsory
Try this:
function ParseDateToLocale(jsonDate) {
var date = new Date(parseInt(jsonDate.substr(6)));
var myDate = new Date(date);
var formatted = myDate.toLocaleString();
return formatted;
}
See it working here: http://jsfiddle.net/2ft3A/.
Try this one, this will help you,
function ParseDate(jsonDate) {
var date = new Date(parseInt(jsonDate.substr(6)));
var merd='';
if(date.getHours()>=12)
{
merd='PM';
}
else
{
merd='AM';
}
var formatted = ("0" + (date.getMonth() + 1)).slice(-2) + "/" + ("0" + date.getDate()).slice(-2) + "/" + date.getFullYear() + " " + date.getHours() + ":" + date.getMinutes() + ":" + "0" + date.getSeconds()+ " " + merd;
return formatted;
}
dateObject.toLocaleTimeString(); (OR) date.getHours() will return 0-24hrs. Base on that value you can append AM or PM

using date in javascript

I have trouble using date in Javascript, in PHP you use something like date("Y-m-d H:i s") to retrieve the specific date and time, how can I achieve this in Javascript? the getMonth() method only returns 1 digit, I really need them to be in 2 digits
Since I made comments on almost all answers, I'd better post my suggestion
DEMO
function pad(num) { return ("0"+num).slice(-2); }
function getDisplayDate() {
var date = new Date();
return date.getFullYear()+
"-"+pad(date.getMonth()+1)+
"-"+pad(date.getDate())+
" "+pad(date.getHours())+
":"+pad(date.getMinutes())+
":"+pad(date.getSeconds());
}
setInterval(function() {
document.getElementById("time").innerHTML=getDisplayDate();
},500);
why dont you add 0 before when you get <10
Try this :
function dateToYMD(date) {
var d = date.getDate();
var m = date.getMonth() + 1;
var y = date.getFullYear();
return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d) + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
}
var d = new Date();
alert(dateToYMD(d));
This code is adjusted based on the pointers given by #mplungjan -- (credits to him please)
Also check out his solution, which is a better one for use with date digits.
var str = 10; // month-digit from getMonth()
function pad(val) {
return "0" + val;
}
var month = str < 10 ? pad(str) : str;
console.log(month);
you can year, minutes, etc from Date class. You can get 2 digits month using some trick like example below. e.g
Date.prototype.getLongMonth = function() {
var month = this.getMonth();
if (String(month).length == 1) month = '0'.concat(month);
return month;
}
var now = new Date();
var theDate = now.getFullYear() + '-' + now.getLongMonth() + '-' + now.getDate() + ' ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
console.log(theDate); // result : 2013-02-17 12:41:2

How to get correct gmt time in Javascript

For using the Amazon mechanical turk API I want to get the current GMT time and show it in ISO format
2011-02-24T20:38:34Z
I am wondering if there is any way to correctly get the gmt time and also be able to reformat it with ISO format. I can use something like now.toGMTString(); but it makes a string out of the date and it is hard to reformat it with ISO.
var year = now.getUTCFullYear()
var month = now.getUTCMonth()
var day= now.getUTCDay()
var hour= now.getUTCHours()
var mins= now.getUTCMinutes()
var secs= now.getUTCSeconds()
var dateString = year + "-" + month + "-" + day + "T" + hour + ":" + mins + ":" + secs + "Z"
You should be using UTC now instead of GMT. (Amounts to almost the same thing now, and it is the new standard anyway)
I believe this will work for you:
Number.prototype.pad = function(width,chr){
chr = chr || '0';
var result = this;
for (var a = 0; a < width; a++)
result = chr + result;
return result.slice(-width);
}
Date.prototype.toISOString = function(){
return this.getUTCFullYear().pad(4) + '-'
+ this.getUTCMonth().pad(2) + '-'
+ this.getUTCDay().pad(2) + 'T'
+ this.getUTCHours().pad(2) + ':'
+ this.getUTCMinutes().pad(2) + ':'
+ this.getUTCSeconds().pad(2) + 'Z';
}
Usage:
var d = new Date;
alert('ISO Format: '+d.toISOString());
Not much more different than every else's answer, but make it built-in to the date object for convenience
function pad(num) {
return ("0" + num).slice(-2);
}
function formatDate(d) {
return [d.getUTCFullYear(),
pad(d.getUTCMonth() + 1),
pad(d.getUTCDate())].join("-") + "T" +
[pad(d.getUTCHours()),
pad(d.getUTCMinutes()),
pad(d.getUTCSeconds())].join(":") + "Z";
}
formatDate(new Date());
Output:
"2011-02-24T21:01:55Z"
This script can take care of it
/* use a function for the exact format desired... */
function ISODateString(d){
function pad(n){return n<10 ? '0'+n : n}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'}
var d = new Date();
document.write(ISODateString(d)); // prints something like 2009-09-28T19:03:12Z

Categories

Resources