I have a date in this format "2012-12-20 21:34:09".
How to format in the format dd/mm/yyyy
You could try
var mydate = '2012-12-20 21:34:09';
var formatteddate = mydate.split(' ')[0].split('-').reverse().join('/');
This should do it.
var date = new Date(Date.parse("2012-12-20 21:34:09"));
var converted = date.getDate() + "/" + (date.getMonth()+1) + "/" + date.getFullYear();
It's worthwhile to note that this will only work in Chrome and Opera. (Thanks to Gaby aka G. Pertrioli)
You could parse the date and the reprint it. Something like this:
var date = new Date( Date.parse( "2012-12-20 21:34:09" ) );
var formattedDate = date.getDate() + "/" + ( date.getMonth() + 1 ) + "/" + date.getFullYear();
None of the other answers handle zero padding, which means that they won't fit the dd/mm/yyyy format for other dates.
var date = new Date("2012-12-20 21:34:09");
var converted = String("0" + date.getDate()).slice(-2);
converted += "/" + String("0" + date.getMonth()+1).slice(-2);
converted += "/" + date.getFullYear();
alert(converted);
Edit
cross-browser version:
var parts = "2012-12-20 21:34:09".split(" ")[0].split("-");
var converted = String("0" + parts[1]).slice(-2);
converted += "/" + String("0" + parts[2]).slice(-2);
converted += "/" + parts[0];
alert(converted);
using the power of RegExp it becomes quite simple:
"2012-12-20 21:34:09".replace(/^(\d+)-(\d+)-(\d+).*/, '$3/$2/$1');
returns "20/12/2012"
Related
I have a datetime that looks like this:
2017-04-17 18:26:03
How can I convert this to this format using javascript or jquery:
17/04/2017 18:26
I found this question which I thought might help me but the answers are converting a timestamp but mine is not a time stamp.
How to convert a DateTime value to dd/mm/yyyy in jQuery?
You can use simple string and array manipulation.
const dateTime = '2017-04-17 18:26:03';
const parts = dateTime.split(/[- :]/);
const wanted = `${parts[2]}/${parts[1]}/${parts[0]} ${parts[3]}:${parts[4]}`;
console.log(wanted);
Additional: If you don't have an environment that supports Template Literals then you can write it like this.
const dateTime = '2017-04-17 18:26:03';
const parts = dateTime.split(/[- :]/);
const wanted = parts[2] + '/' + parts[1] + '/' + parts[0] + ' ' + parts[3] + ':' + parts[4];
console.log(wanted);
You could use a regular expression within a replace call:
input.replace(/^(\d+)-(\d+)-(\d+)(.*):\d+$/, '$3/$2/$1$4');
var input = '2017-04-17 18:26:03';
var result = input.replace(/^(\d+)-(\d+)-(\d+)(.*):\d+$/, '$3/$2/$1$4');
console.log(result);
Explanation
^: match start of the string.
(\d+): capture group that matches digits. A captured group can be back-referenced with $1 for the first group, $2 for the second ... etc. in the second argument.
:\d+$: match a colon followed by digits and the end of the string ($): as this is not captured, this part (seconds) will be omitted in the result.
try to create a function that format your date. here is an example that i wrote.
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;
}
console.log(formate("2017-04-17 18:26:03"));
This will do the work:
var timestamp = Date.parse('2017-04-17 18:26:03'); // 1492467963000
var date = new Date(timestamp).toJSON(); // "2017-04-17T22:26:03.000Z"
var dateStr = date.slice(0, 10).split("-").reverse().join("/") // "17/04/2017"
.concat(' ')
.concat(date.slice(11, 16)); // "22:26"
console.log(dateStr)
"17/04/2017 22:26"
Using jquery/Javascript how can i convert a value with date 1111-2016-10-26 INTO 1111 - 10/26/2016 format ?
i tried below code but it did not helped.
var date = new Date('2010-10-11');
alert((date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear());
If you just want to convert without any date validations you can do it with string functions. Or if you want to use date functions, apply it only to that part of the string after splitting the string. Nothing fancy.
Use normal Date constructor (year,[month,[date...]]) when creating Date objects, passing non-standard formats is not recommended as the implementations are browser dependant.
var string = "1111-2016-10-26";
var a = string.split('-');
var number = a[0];
var date = a[2] + '/' + a[3] + '/' + a[1];
console.log(number + '-' + date);
var string = '1111-2010-10-11';
var a = string.split('-').map(Number);
var date = new Date(a[1], a[2] - 1, a[3]);
var dateString = ((date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear());
console.log(a[0]+ '-' + dateString);
I have this date:
2015-05-28T23:00:00.000Z
I need to convert it to the local date which would be (in this format):
29/05/2015
I would expect the above formatted date to be correct based on the date string above.
How would I do this?
Thank you
convert it to Date object:
var dateString = '2015-05-28T23:00:00.000Z';
var date = new Date(dateString)
then you cant format it:
var formatedDate = date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear();
But you can also use moment.js
moment(dateString).format('DD/MM/YYYY');
It's been well covered elsewhere that using the Date constructor to parse strings isn't a good idea. The format in the OP is consistent with ES5 and will be parsed correctly by modern browsers, but not IE 8 which still has a significant user share.
Parsing the string manually isn't difficult:
function isoStringToDate(s) {
var b = s.split(/\D/);
return new Date(Date.UTC(b[0], --b[1], b[2], b[3], b[4], b[5], b[6]));
}
Then to format it:
function dateToDMY(d) {
function z(n){return (n<10?'0':'') + n}
return z(d.getDate()) + '/' + z(d.getMonth()+1) + '/' + d.getFullYear();
}
console.log(dateToDMY(isoStringToDate('2015-05-28T23:00:00.000Z'))); // 29/05/2015
To be consistent with ES5, the parse function should check values aren't out of range but if you're confident of the correctness of the string that shouldn't be necessary.
Thank you for your replies.
I've got it formatted by doing:
var d = new Date('2015-05-28T23:00:00.000Z');
var n = d.getDate() + '/' + (d.getMonth() +1 ) + '/' + d.getFullYear();
document.getElementById("demo").innerHTML = n;
Please add the following code in script
<script>
var d = new Date("2015-05-28T23:00:00.000Z");
var str=d.toString();
var date = new Date(str),
mnth = ("0" + (date.getMonth()+1)).slice(-2),
day = ("0" + date.getDate()).slice(-2);
var local_date=[ date.getFullYear(), mnth, day ].join("/"); //yyyy/mm/dd
</script>
Hope it works.Thank you
how can I get the date in this format [mm/dd/yy] using javascript. I am struggling to get the 'year' to a 2 digit figure as opposed to the full 4 digits. Thanks!
var date = new Date();
var datestring = ("0" + (date.getMonth() + 1).toString()).substr(-2) + "/" + ("0" + date.getDate().toString()).substr(-2) + "/" + (date.getFullYear().toString()).substr(2);
This guarantees 2 digit dates and months.
Try this:
HTML
<div id="output"></div>
JS
(function () {
// Get current date
var date = new Date();
// Format day/month/year to two digits
var formattedDate = ('0' + date.getDate()).slice(-2);
var formattedMonth = ('0' + (date.getMonth() + 1)).slice(-2);
var formattedYear = date.getFullYear().toString().substr(2,2);
// Combine and format date string
var dateString = formattedMonth + '/' + formattedDate + '/' + formattedYear;
// Reference output DIV
var output = document.querySelector('#output');
// Output dateString
output.innerHTML = dateString;
})();
Fiddle: http://jsfiddle.net/kboucher/4mLe1Lrd/
How About this for the year
String(new Date().getFullYear()).substr(2)
And since you need your Month from 01 through 12 do this
var d = new Date("2013/8/3");
(d.getMonth() < 10 ? "0" : "") + (d.getMonth() + 1)
Do the same thing for days, Minutes and seconds
Working Demo
I need to output the current UTC datetime as a string with the following format:
YYYY/mm/dd hh:m:sec
How do I achieve that with Javascript?
You can build it manually:
var m = new Date();
var dateString = m.getUTCFullYear() +"/"+ (m.getUTCMonth()+1) +"/"+ m.getUTCDate() + " " + m.getUTCHours() + ":" + m.getUTCMinutes() + ":" + m.getUTCSeconds();
and to force two digits on the values that require it, you can use something like this:
("0000" + 5).slice(-2)
Which would look like this:
var m = new Date();
var dateString =
m.getUTCFullYear() + "/" +
("0" + (m.getUTCMonth()+1)).slice(-2) + "/" +
("0" + m.getUTCDate()).slice(-2) + " " +
("0" + m.getUTCHours()).slice(-2) + ":" +
("0" + m.getUTCMinutes()).slice(-2) + ":" +
("0" + m.getUTCSeconds()).slice(-2);
console.log(dateString);
No library, one line, properly padded
const str = (new Date()).toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ");
It uses the built-in function Date.toISOString(), chops off the ms, replaces the hyphens with slashes, and replaces the T with a space to go from say '2019-01-05T09:01:07.123' to '2019/01/05 09:01:07'.
Local time instead of UTC
const now = new Date();
const offsetMs = now.getTimezoneOffset() * 60 * 1000;
const dateLocal = new Date(now.getTime() - offsetMs);
const str = dateLocal.toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ");
With jQuery date format :
$.format.date(new Date(), 'yyyy/MM/dd HH:mm:ss');
https://github.com/phstc/jquery-dateFormat
Enjoy
I wrote a simple library for manipulating the JavaScript date object. You can try this:
var dateString = timeSolver.getString(new Date(), "YYYY/MM/DD HH:MM:SS.SSS")
Library here:
https://github.com/sean1093/timeSolver
Not tested, but something like this:
var now = new Date();
var str = now.getUTCFullYear().toString() + "/" +
(now.getUTCMonth() + 1).toString() +
"/" + now.getUTCDate() + " " + now.getUTCHours() +
":" + now.getUTCMinutes() + ":" + now.getUTCSeconds();
Of course, you'll need to pad the hours, minutes, and seconds to two digits or you'll sometimes get weird looking times like "2011/12/2 19:2:8."
Alternative to answer of #JosephMarikle
If you do not want to figth against timezone UTC etc:
var dateString =
("0" + date.getUTCDate()).slice(-2) + "/" +
("0" + (date.getUTCMonth()+1)).slice(-2) + "/" +
date.getUTCFullYear() + " " +
//return HH:MM:SS with localtime without surprises
date.toLocaleTimeString()
console.log(fechaHoraActualCadena);
Posting another script solution DateX (author)
for anyone interested
DateX does NOT wrap the original Date object, but instead offers an identical interface with additional methods to format, localise, parse, diff and validate dates easily. So one can just do new DateX(..) instead of new Date(..) or use the lib as date utilities or even as wrapper or replacement around Date class.
The date format used is identical to php date format.
c-like format is also supported (although not fully)
for the example posted (YYYY/mm/dd hh:m:sec) the format to use would be Y/m/d H:i:s eg
var formatted_date = new DateX().format('Y/m/d H:i:s');
or
var formatted_now_date_gmt = new DateX(DateX.UTC()).format('Y/m/d H:i:s');
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC