21

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
  • 24,780
  • 27
  • 82
  • 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

11 Answers11

24

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ó
  • 807,428
  • 183
  • 922
  • 838
  • 1
    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
23

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

function reformatDate(dateStr)
{
  var dArr = dateStr.split("-");  // ex input: "2010-01-18"
  return dArr[2]+ "/" +dArr[1]+ "/" +dArr[0].substring(2); //ex output: "18/01/10"
}
Andy E
  • 338,112
  • 86
  • 474
  • 445
21

Do it in one line:

date.split("-").reverse().join("-");
// 2021-09-16 => 16-09-2021
cmcodes
  • 1,559
  • 19
  • 24
6

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,380
  • 2
  • 17
  • 22
3

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

alemjerus
  • 8,023
  • 3
  • 32
  • 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,210
  • 12
  • 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,741
  • 1
  • 16
  • 27
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,729
  • 1
  • 15
  • 31
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
  • 27,056
  • 15
  • 80
  • 110
0

Using toLocaleDateString is the best way to convert any date format:

const date: Date = new Date('2023-04-11');
return date.toLocaleDateString('en-US', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    timeZone: 'UTC'
})
Ali
  • 125
  • 2
  • 4
-1
function formatDate(date) {

  const [year, month, day] = date.split('-');

  return `${day}.${month}.${year}`;

};
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
V.S.
  • 1
  • 2
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the [help center](https://stackoverflow.com/help/how-to-answer). – Ethan Sep 24 '22 at 21:39