How to format existing date using JavaScript/jQuery - javascript

I am trying to format date time using JavaScript/jQuery but it's not happening. My code is below.
<div id="divID"></div>
<script>
var formatDate = function(date){
return date.getDate() + "/" + date.getMonth() + "/" +date.getYear() + " "+ date.getHours() + ":" + date.getMinutes() + ":" + date.getMintutes() + ":" + date.getSeconds();
}
var timestamp="2016-12-16 07:58:30 AM ";
var date= new Date(timestamp);
document.getElementById('divID').innerHTML = formatDate(date);
</script>
Here I have the existing time 2016-12-16 07:58:30 AM and I need change it to 16-12-2016 07:58:30 AM but here I could not get the proper output.

Your code has a few issues:
You have a syntax error, you're calling getMintutes()
You appear to be attempting to show the minutes twice, so you can remove one of those calls
getFullYear() fits your needs better than getYear()
You should use - not / to delimit the date values.
You can add AM or PM to the end of the string by checking if hours < 12
Your timestamp string isn't valid. It should not contain 'AM' or 'PM' - hence why the code doesn't work in Firefox.
With that in mind, try this:
var formatDate = function(date) {
return date.getDate() + "-" + date.getMonth() + "-" + date.getFullYear() + " " + ('0' + date.getHours()).slice(-2) + ":" + ('0' + date.getMinutes()).slice(-2) + ":" + ('0' + date.getSeconds()).slice(-2) + ' ' + (date.getHours() < 12 ? 'AM' : 'PM');
}
var timestamp = "2016-12-16 07:58:30";
var date = new Date(timestamp);
document.getElementById('divID').innerHTML = formatDate(date);
<div id="divID"></div>
You could use a library to make the date formatting logic simpler, but it's rather wasteful to load an entirely library when a single line of code works fine.

The timestamp you are using will return an invalid date so you should remove the AM. Using moment.js you can do it like this:
var timestamp = "2016-12-16 07:58:30";
var formattedDate = moment(timestamp).format('DD-MM-YYYY h:mm:ss A');
console.log(formattedDate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.5.1/moment.min.js"></script>

you can use a library named moment.js http://momentjs.com/
var date = new Date();
moment(date).format('DD-MM-YYYY HH:mm:ss A')

jQuery dateFormat is a separate plugin. You need to load that explicitly using a <script> tag.

You can use JQuery UI Datepicker for getting the formatted date like the following.
let myDate = '2020-11-10';
$.datepicker.formatDate('dd-M-yy', new Date(myDate));
The above code will return 10-Nov-2020.

You can get the desired output using JQuery UI Datepicker Widget as shown below.
var timestamp="2016-12-16 07:58:30 AM ";
var desiredTimestamp = $.datepicker.formatDate('dd-mm-yy', new Date(timestamp.split(' ')[0])) + ' ' + timestamp.split(' ')[1] + ' ' + timestamp.split(' ')[2];

Related

Javascript change the data in some data

I have a variable that's returning the following content:
{
"id":1,
"refnumber":3,
"active":false,
"date":"2017-09-14T23:00:00.000Z",
"addons":0,
"age":0
}
If you look at the data field I need a way of changing the data on that field to yyyy-mm-dd.
In other words .. if we take this example as a reference I would need the data field value:
This:
2017-09-14T23:00:00.000Z
To be changed to this:
2017-09-14
How can I do this?
You should just be able to slice away the trailing characters.
data.date = data.date.slice(0, 10);
This works because your data format is in a predictable form where the month and day have a 0 padding.
I recommend a library called momentjs for all your javascript date manipulation needs.
https://momentjs.com/
With it, you can do what you want easily: moment(data.date).format('YYYY-MM-DD')
Note that your JSON is invalid because the date string is not properly quoted, but assuming it's corrected and that your JSON object is named myObject, the following would work:
var date = new Date(myObject.date); //your string will become a date object
//now operate on that date object by extracting the year, month,
//and day into a string
console.log(date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate());
Well you could convert the string to date and then format it
Here is an example
function formate(date) {
if (typeof date == "string")
date = new Date(date);
var day = (date.getDate() <= 9 ? "0" + date.getDate() :
date.getDate());
var month = (date.getMonth() + 1 <= 9 ? "0" +
(date.getMonth() + 1) : (date.getMonth() + 1));
var dateString = day + "-" + month + "-" +
date.getFullYear() + " " + date.getHours() + ":" +
date.getMinutes();
return dateString;
}

JavaScript date and time formatting,

I have read a lot of thread about the subject, but i'm not much into programming... i've made some tests but never acheive what i wanted.
Here we have a html template we have to modify to suit our needs.
here the code i have to edit:
<p id="DATE"></p>
<script>
var d = new Date();
document.getElementById("DATE").innerHTML = d.toString();
</script>
Its giving me the date OK...but not i the format i want...
the format i want is... DD-MM-YYYY HH:MM
Simple has that :)
Its been a couple of hours and i can't do it... Can anyone help with a code i just can copy/paste in my html file.
As opposed to using an external JavaScript library for a simple task. You should be able to achieve the same with Vanilla js.
Refer to this:
Where can I find documentation on formatting a date in JavaScript?
In short:
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();
console.log(curr_date + "-" + curr_month + "-" + curr_year + " " + curr_hour + ":" + curr_min);
The above snippet should have all the code you need.
For your specific implementation, you will need to do the below:
<script>
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();
var formattedDate = curr_date + "-" + curr_month + "-" + curr_year + " " + curr_hour + ":" + curr_min;
document.getElementById("DATE").innerHTML = formattedDate;
</script>
A function for the format you require is fairly simple. The following will return a string for a provided Date, or the current date if none passed.
function formatDate(date) {
var d = date || new Date();
function z(n){return (n<10?'0':'')+n}
return z(d.getDate()) + '-' +
z(d.getMonth()+1) + '-' +
d.getFullYear() + ' ' +
z(d.getHours()) + ':' +
z(d.getMinutes());
}
document.write(formatDate());
BTW, you can't use the same token for two separate parts. While there is no standard or even consistency for formatting tokens, your format would be more commonly expressed as:
DD-MM-YYYY HH:mm
Which is compatible with moment.js and a few others, though there are many other token sets to represent the same format.
To achieve your goal simply try following codes:
First of all, inside the head tag add the below line of code:
<script src="https://rawgit.com/moment/moment/2.2.1/min/moment.min.js"></script>
Finally, change your existing line of code:
document.getElementById("DATE").innerHTML = moment(d).format('DD-MM-YYYY HH:MM');
Happy coding :)

How to set common format for toLocaleString?

I use JS function toLocaleString for date formatting. How can I set one common format for all clients like:
2015-10-29 20:00:00
That I do parsong at PHP by -
I think you would have to manually parse it into that format, which actually isn't too bad. What Date.toLocaleString() returns is a format of:
MM/DD/YYYY, HH:MM:SS
Here's my code snippet to help you out:
// Parse our locale string to [date, time]
var date = new Date().toLocaleString('en-US',{hour12:false}).split(" ");
// Now we can access our time at date[1], and monthdayyear # date[0]
var time = date[1];
var mdy = date[0];
// We then parse the mdy into parts
mdy = mdy.split('/');
var month = parseInt(mdy[0]);
var day = parseInt(mdy[1]);
var year = parseInt(mdy[2]);
// Putting it all together
var formattedDate = year + '-' + month + '-' + day + ' ' + time;
You can set the format as described (yyyy-mm-dd hh:mm:ss) by adding the locale parameter, like this:
toLocaleString("sv-SE")
References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
https://www.w3schools.com/Jsref/jsref_tolocalestring.asp
https://www.w3schools.com/Jsref/tryit.asp?filename=tryjsref_tolocalestring_date_all
you can use moment.js library which has many features to work with date & time you can easily format a date with that.
here is an example
moment().format('YYYY-MM-DD HH:mm:ss'); // will print in 2015-10-29 20:00:00 format
Moment.js
before doing what i provide please read this and this
var el = document.getElementById('dbg');
var log = function(val){el.innerHTML+='<div><pre>'+val+'</pre></div>'};
var pad = function(val){ return ('00' + val).slice(-2)};
Date.prototype.myFormattedString = function(){
return this.getFullYear() + '-' +
pad( (this.getMonth() + 1) ) + '-' +
pad( this.getDate() ) + ' ' +
pad( this.getHours() ) + ':' +
pad( this.getMinutes() ) + ':' +
pad( this.getSeconds() )
;
}
var curDate = new Date();
log( curDate )
log( curDate.toLocaleString() )
log( curDate.myFormattedString() )
<div id='dbg'></div>

Date parse format from T with time to mm/dd/yyyy with javascript or jquery

I have the following value:
javascript variable:
"2015-10-14T17:54:19.033"
I want to end up with
mm/dd/yyyy
e.g.
10/14/2015
I was trying to do
var date = month[d.getMonth()] + " " + d.getDay()+ ", " + d.getFullYear();
Here is my Fiddle
http://jsfiddle.net/bthorn/7ptcedt4/
var d = new Date('2015-10-14T17:54:19.033');
var date = d.getMonth().toString() + "/" + d.getDay().toString() + "/" + d.getFullYear().toString();
console.log(date);
Something is NOT right: I am getting
9/3/2015
You can use this:
var date = new Date("2015-10-14T17:54:19.033");
var formatedDateString = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
Or use moment.js
var formatedDateString = moment("2015-10-14T17:54:19.033").format('MM/dd/YYYY');
Or may you consider create your own date format function.
PS.: javascript months are 0-indexed, so for the correct month you should use (date.getMonth() + 1)

Format date in jQuery

var date = "Fri Jan 29 2012 06:12:00 GMT+0100";
How can i show this in format 2012-01-29 06:12 ?
In PHP is function ->format. In Javascript is also format, but if i try use this then i have error:
now.format is not a function
var now = new Date();
console.log(now.format("isoDateTime"));
http://jsfiddle.net/6v9hD/
I would like receive format: 2012-01-29 06:12
This question is a duplicate (see: How to get current date in jquery?).
By modifying my solution from the other question, I got:
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var hour = d.getHours();
var minute = d.getMinutes();
var second = d.getSeconds();
var output = d.getFullYear() + '-' +
((''+month).length<2 ? '0' : '') + month + '-' +
((''+day).length<2 ? '0' : '') + day + ' ' +
((''+hour).length<2 ? '0' :'') + hour + ':' +
((''+minute).length<2 ? '0' :'') + minute + ':' +
((''+second).length<2 ? '0' :'') + second;
See this jsfiddle for a proof: http://jsfiddle.net/nCE9u/3/
You can also enclose it within function (demo is here: http://jsfiddle.net/nCE9u/4/):
function getISODateTime(d){
// padding function
var s = function(a,b){return(1e15+a+"").slice(-b)};
// default date parameter
if (typeof d === 'undefined'){
d = new Date();
};
// return ISO datetime
return d.getFullYear() + '-' +
s(d.getMonth()+1,2) + '-' +
s(d.getDate(),2) + ' ' +
s(d.getHours(),2) + ':' +
s(d.getMinutes(),2) + ':' +
s(d.getSeconds(),2);
}
and use it like that:
getISODateTime(new Date());
or:
getISODateTime(some_other_date);
EDIT: I have added some improvement to the function, as proposed by Ates Goral (also decreased its readability in favour of code comments).
Datejs.toString('yyyy-MM-dd HH:mm') should do the trick
Unfortunately, in Javascript, Date does not have a format() method.
Check out http://fisforformat.sourceforge.net for some nice formatting methods.
Use a library like Datejs or perhaps this tweet-sized implementation:
https://gist.github.com/1005948
var str = formatDate(
new Date(),
"{FullYear}-{Month:2}-{Date:2} {Hours:2}:{Minutes:2}");
I think this could be help you:date.format.js
var now = new Date();
now.format("m/dd/yy");
// Returns, e.g., 6/09/07
// Can also be used as a standalone function
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");
// Saturday, June 9th, 2007, 5:46:21 PM
// You can use one of several named masks
now.format("isoDateTime");
You can use something like this(include date.js ) :
Date.parse(yourDate).toISOString();
so the date will have ISO 8601 format.

Categories

Resources