2

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?

Community
  • 1
  • 1
David Hope
  • 1,426
  • 4
  • 21
  • 50
  • 3
    Why do you want 2 minutes to be added to it? – trincot Apr 14 '17 at 17:13
  • 2
    Your `datetime` it's just a string , right? – Xotic750 Apr 14 '17 at 17:14
  • @trincot, LOL.. that was a typo. sorry... I dont want 2 minutes to be added to it. – David Hope Apr 14 '17 at 17:14
  • @Xotic750, correct. – David Hope Apr 14 '17 at 17:15
  • 2
    why you don't use momentjs? – Cristian Szpisjak Apr 14 '17 at 17:15
  • @CristianSzpisjak, because it bloated and its an overkill for such a simple task. – David Hope Apr 14 '17 at 17:16
  • 3
    Momentjs is lightweight library that will take care of all the time conversion and parsing needs. Is good for the long term. Don't try to reinvent the wheel. – Cristian Szpisjak Apr 14 '17 at 17:20
  • 1
    It's not really overkill when what you're attempting to do is reinventing the wheel. Regex-based solutions are cumbersome and definitely not fool-proof, and it is very easy to miss edge cases when writing your own parser. [Moment.js](https://momentjs.com) or even [d3's date time parser](d3 parse datetime) are good libraries to work with. – Terry Apr 14 '17 at 17:20
  • 1
    @CristianSzpisjak Ha, great minds think alike :) – Terry Apr 14 '17 at 17:20
  • I'm confused. If the task is so simple, why are you asking how to do it? You're correct in that momen.js would be overkill but only if your input format never changes. If it never changes just parse out the pieces and reassemble? – gforce301 Apr 14 '17 at 17:20
  • @gforce301, look at the answers given bellow. specifically look at the answer given by Xotic750.. thats why i said using a bloated library is an overkill and no need for it either. – David Hope Apr 14 '17 at 17:22
  • @DavidHope I think you missed the point of my comment. "If the task is so simple, why are you asking how to do it?" in reference to your comment "because it bloated and its an overkill for such a simple task.: – gforce301 Apr 14 '17 at 17:34
  • @gforce301, simple in terms of not needing a library to achieve it.. that's what i meant. :)... I'm not being big headed or anything.. i just said its simple because I knew it can be done in 2 or 3 lines of code and it doesn't require momentjs. – David Hope Apr 14 '17 at 17:39

4 Answers4

6

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);
Xotic750
  • 22,914
  • 8
  • 57
  • 79
  • remove the ``` from around the `${parts[2]}/${parts[1]}/${parts[0]} ${parts[3]}:${parts[4]}`. it took me hours to figure out why this code was throwing an error. other than that it works fine. – David Hope Apr 15 '17 at 14:42
  • They are required with how it is currently written. It is a [Template Literal](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals) If you remove them then you must use string concatenation. – Xotic750 Apr 15 '17 at 16:24
  • I don't know how, without them you should get `SyntaxError: Unexpected token {` Can you provide a [jsfiddle](https://jsfiddle.net/) that demonstrates it working without them? – Xotic750 Apr 15 '17 at 17:01
5

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.
trincot
  • 317,000
  • 35
  • 244
  • 286
2

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"));
Ranadip Dutta
  • 8,857
  • 3
  • 29
  • 45
Alen.Toma
  • 4,684
  • 2
  • 14
  • 31
1

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"
streetturtle
  • 5,472
  • 2
  • 25
  • 43
  • What's wrong? He knows how to convert timestamp to date, I showed how to convert string to timestamp... If I misunderstood the question it's not the reason to downvote. Just let me know what I did wrong in comments to my answer - it's simple. – streetturtle Apr 14 '17 at 17:17
  • Unfortunately there are quite a few trigger happy fingers on STO. you could be giving a correct answer and still get downvoted. same goes for the questions.. you could be asking a valid question and still get downvoted. – David Hope Apr 14 '17 at 17:20
  • 1
    I didn't downvote your answer. You should not make reference to a 'link'. You should explain what is in the 'link'. The answer is a little confusing. – Rudy Vissers Apr 14 '17 at 17:41