17

I am trying to create a function on javascript to bring the date from my database in format (yyyy-mm-dd) and display it on the page as (dd/mm/yy).

I would appreciate any help.

Thanks.

PD: Let me know if you need more clarification.

Amra
  • 23,781
  • 26
  • 80
  • 92
  • 1
    how do you get the date from your database ? – Valentin Rocher Jan 18 '10 at 14:49
  • http://stackoverflow.com/search?q=convert+date – Upperstage Jan 18 '10 at 14:54
  • 3
    Can I make a plea for leaving it as it is? `yyyy-mm-dd` is a perfectly readable date format. `dd/mm/yy` is an ambiguous horror. (Is it UK or US date ordering? What century? I can't immediately tell by looking at it.) – bobince Jan 18 '10 at 16:29
  • @bobince: it depends on the context of where it is used. If it is a web app that is only used in a single country or internally the users will know what the common date format is and are probably more confused in seeing a format they didn't expect. Furthermore, yyyy-mm-dd is not a very common format used in UIs and it could for novice users still cause ambiguity (is it yyyy-mm-dd or yyyy-dd-mm?). – Tom van Enckevort Jan 21 '10 at 10:13

9 Answers9

23

If you're sure that the date that comes from the server is valid, a simple RegExp can help you to change the format:

function formatDate (input) {
  var datePart = input.match(/\d+/g),
  year = datePart[0].substring(2), // get only two digits
  month = datePart[1], day = datePart[2];

  return day+'/'+month+'/'+year;
}

formatDate ('2010/01/18'); // "18/01/10"
Christian C. Salvadó
  • 769,263
  • 179
  • 909
  • 832
  • Just in case anybody wants to show the full year i.e the 4 digits use this: year = datePart[0].substring(0,4) Only adding as it might not be immediately obvious. Thanks for the answer! – Jonathan Coffey Jan 10 '16 at 01:38
20

Easiest way assuming you're not bothered about the function being dynamic:

function reformatDate(dateStr)
{
  dArr = dateStr.split("-");  // ex input "2010-01-18"
  return dArr[2]+ "/" +dArr[1]+ "/" +dArr[0].substring(2); //ex out: "18/01/10"
}
Andy E
  • 326,646
  • 82
  • 467
  • 441
5

Use any one of this js function to convert date yyyy/mm/dd to dd/mm/yy

Type 1

function ChangeFormateDate(oldDate){
   var p = dateString.split(/\D/g)
   return [p[2],p[1],p[0] ].join("/")
}

Type 2

function ChangeFormateDate(oldDate)
{
   return oldDate.toString().split("/").reverse().join("/");
}

You can call those Functions by using :

ChangeFormateDate("2018/12/17") //"17/12/2018"
Anandan K
  • 1,184
  • 2
  • 15
  • 20
5

Do it in one line:

date.split("-").reverse().join("-");
// 2021-09-16 => 16-09-2021
cmcodes
  • 1,154
  • 15
  • 21
3

Use functions getDateFromFormat() and formatDate() from this source: http://mattkruse.com/javascript/date/source.html
Examples are also there

alemjerus
  • 7,623
  • 3
  • 31
  • 40
2

You may also want to look into using date.js:

http://www.datejs.com

To futureproof your application, you may want to return time in a UTC timestamp and format with JavaScript. This'll allow you to support different formats for different countries (in the U.S., we are most familiar with DD-MM-YYYY, or instance) as well as timezones.

Ikai Lan
  • 2,200
  • 11
  • 13
2

Try this:

function convertDate(dateString){
  var p = dateString.split(/\D/g)
  return [p[2],p[1],p[0] ].join("-")
}

convertDate("2001-9-11")//"11-9-2001"
Faridul Khan
  • 1,387
  • 1
  • 13
  • 26
1

You can also use destructuring and template literals in case you are sure that you will always receive a date in YYYY-MM-DD.

const changeDateFormatTo = date => {
  const [yy, mm, dd] = date.split(/-/g);
  return `${dd}/${mm}/${yy}`;
};

const formattedDate = changeDateFormatTo("2019-08-14");
console.log(`Formatted date is: ${formattedDate}`);
Hardik Pithva
  • 1,670
  • 1
  • 14
  • 30
0

It's a simple case, but everyone is using string methods! This is a little barbaric :-)

The Date object is all set up for this, and will get you much further once you get the hang of it. Your date has no timezone, so I suggest you force UTC both on the way in and the way out. The en-GB locale forces dd-mm, but you should bear in mind that English speaking users are split down the middle on date format, and each half finds the other's format totally confusing. You should really try and make your numeric date format adapt to the preferences of the user, especially since it's easy!

So...

new Vue({
  el: '#vueRoot',
  data: {kennedy: '1963-11-22'},
  computed:{
    kennedyDdmm(){
      return new Date(this.kennedy + 'T00:00:00Z')
      .toLocaleDateString('en-GB',{timeZone:'UTC'})
    },
    kennedyAuto(){
      return new Date(this.kennedy + 'T00:00:00Z')
      .toLocaleDateString([],{timeZone:'UTC'})
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id='vueRoot'>
  <h1>in => {{kennedy}}</h1>
  <h1>dd-MM-yy => {{kennedyDdmm}}</h1>
  <h1>respect user prefs => {{kennedyAuto}}</h1>
</div>
bbsimonbb
  • 24,062
  • 11
  • 66
  • 99