How to convert a date (string) to another format using Javascript?

Asked

Viewed 360 times

-2

I have the following string:

2016-06-08 - 10:08 

I need to convert this string to the other format:

08-06-2016 10:08

How should I proceed?

   function dateFormat(date) {
      inputFormat = new java.text.SimpleDateFormat('dd-MM-yyyy');
      inputText = "2012-11-17";
      date = inputFormat.parse(inputText);
      outputText = inputFormat.format(date);
      alert(outputText);
        };

  • All you have is string, just manipulate and create the format you want. What code you have so far?

  • Can you help me?

  • What code do you have so far?

  • I updated @Paulohdsousa

  • Where did you get java.text.Simpledateformat?

  • is a java class. I use Rhino javascript, a java implementation.

  • Da uma olhada nisso inputText = new Date('2012-11-17');
alert(inputText.getDate() +'-'+ inputText.getMonth()+'-'+ inputText.getFullYear());

Show 2 more comments

2 answers

-2


If your string follows the same pattern, you can change the position of the letters

var datas = "2016-06-08 - 10:08 ";
var novaData = (datas[8]+datas[9]+datas[4]+datas[5]+datas[6]
+datas[7]+datas[0]+datas[1]+datas[2]+datas[3]+datas[10]+datas[11]
+datas[12]+datas[13]+datas[14]+datas[15]+datas[16]+datas[17]);
alert(novaData);

https://jsfiddle.net/p9u2w5gb/

-2

Why don’t you use the split method to separate the date by the separator - and store it in an array and then just use the Reverse() method to invert the e array.e...

    • 1 for the effort and argument. We need it here. Congratulations. Your idea is totally valid and stuff, including one of the best, but I still need to be sure the fastest way, because I need to perform this procedure hundreds of times in a loop.
  • Thanks for the comments I’m starting now so I really need the criticism and recommendations, in the next reply I’ll be more specific thank you.

  • Hi Moses, welcome to the site. The ideal would be you [Dit] and detail this answer, otherwise it may end up deleted or converted into comment. Here you can always edit your posts to improve them, include more details at any time.

  • Thanks for the tip. I will detail more in any post.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.