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"
Related
I'm trying to convert this 13 digit Unix timestamp (1563398686957) to YYYYMMDD format using Javascript. How can I do this?
I have divided the 1563398686957/1000 and tried to get the first 10 digits but converting from Number to String and back gives me an error and is not there right way to do it if I am looping for many timestamps.
var newCreateDate = 1563398686957 / 1000;
var newTimestamp = Array();
for (let i = 0; i < newCreateDate.length; i++) {
temp_timestamp = String(newCreateDate[i].slice(0, 9));
newTimestamp.push(Number(temp_timestamp));
}
You can pass timestamp into Date:
var unixts = 1563398686957;
var date = new Date(unixts);
var fdate = date.getFullYear() + '/' + ("0" + (date.getMonth() + 1)).slice(-2) + '/' + ("0" + date.getDate()).slice(-2);
console.log(fdate);
new Date(1563398686957).toISOString().substr(0, 10)
Will give you the date in this form: 2019-07-17
new Date(1563398686957).toISOString().substr(0, 10).replace(/-/g, '/')
Will change the dashes to slashes, if you prefer, and...
new Date(1563398686957).toISOString().substr(0, 10).replace(/-/g, '')
Would give you 20190717.
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);
What is the best way to convert the following string to a javascript date string format of MM/DD/YYYY?
"25-AUG-11"
The best way is that given by jmeans in the comment to the question.
When given a string representing a date in one format, then the "best way" to covert it to another format is to first parse it to a date, then format the date to the string you want.
Unless this is a one-time conversion, don't waste your time writing code to format and parse dates! This is a solved problem that is implemented by many thoroughly tested libraries. If you are doing anything that involves date handling and computation, doing things on your own can be error-prone.
One good lightweight date library is moment.js.
Include moment.js like this:
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.0.0/moment.min.js"></script>
Then the JavaScript code for your particular example can be:
alert(moment("25-AUG-11", "DD-MMM-YY").format("MM/DD/YYYY"));
Live demo here
Note: Because you had "AUG" in your input string, you might need to tell the library to use English to parse the "MMM" part if your computer's locale does not use the English language.
Someday we will all speak ISO-8601. #rant :)
Use can use Date object method:
ToISOString()
This coverts date to string according to ISO standard
OR
Use :::toLocaleDateString()
You could use something like this:
var months={
"JAN":1,
"FEB":2,
//... other months
"DEC":12
}
var r=/(\d{1,2})\-(\w+)?\-(\d{1,2})/;
var replaceFunction=function(){
var years=parseInt(arguments[3],10);
var m=months[arguments[2]];
var days=arguments[1]
if(m<9){
m="0"+m;
}
if(days.length===1){
days="0"+days;
}
if(years>50){
years="19"+years;
}else{
years="20"+years;
}
return m+"/"+days+"/"+years;
};
console.log("5-JAN-14".replace(r,replaceFunction));
console.log("25-FEB-98".replace(r,replaceFunction));
You can use this JavaScript function to achieve that:
function formatDate(dateparam) {
var dateObj = new Date(Date.parse(dateparam));
var date = dateObj.getDate();
date = (date.toString().length == 1) ? "0" + date : date;
var month = dateObj.getMonth() + 1;
month = (month.toString().length == 1) ? "0" + month : month;
var year = dateObj.getFullYear();
return month + "/" + date + "/" + year;
}
document.write(formatDate("25-AUG-11"));
//returns "08/25/2011"
"Best" is relative and you haven't provided any criteria. Here's one way using plain string manipulation:
function reFormatDateString(s) {
s = s.split('-');
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'};
return months[s[1].toLowerCase()] + '/' + s[0] + '/' + s[2];
}
alert(reFormatDateString('25-AUG-11')); // 08/25/2011
However, likely you want to deal with the two digit year more specifically.
// The format "MM/DD/YYYY" isn't a "javascript" format, it's a US format.
function reFormatDateString1(s) {
s = s.split('-');
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'};
var m = +s[2];
s[2] = m < 100? (m < 50? m + 2000 : m + 1900) : m;
return months[s[1].toLowerCase()] + '/' + s[0] + '/' + s[2];
}
Here's another version that uses a date object:
function reFormatDateString2(s) {
s = s.split('-');
var months = {jan:0, feb:1, mar:2, apr:3, may:4, jun:5,
jul:6, aug:7, sep:8, oct:9, nov:10, dec:11};
function z(n){return (n<10? '0' : '') + n;}
// Convert 2 digit year. If < 50, assume 21st century,
// otherwise assume 20th.
// Adjust range to suit
if (s[2].length == 2) {
if (s[2] < 50 ) {
s[2] = +s[2] + 2000;
} else {
s[2] = +s[2] + 1900;
}
}
var d = new Date(s[2], months[s[1].toLowerCase()], s[0]);
return z(d.getMonth() + 1) + '/' + z(d.getMonth()+1) + '/' + z(d.getFullYear());
}
You choose "best".
This seems to be working fine.
var date = new Date("25-AUG-11");
console.log(date.getMonth() + '/' + date.getDate() + '/' + date.getFullYear());
Working Fiddle
You just need to add 0 at starting of month value which can be done easily with string length comparison.
Source
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"
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