将日期 yyyy/mm/dd 转换为 dd/mm/yy 的 Javascript 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2086744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:43:05  来源:igfitidea点击:

Javascript function to convert date yyyy/mm/dd to dd/mm/yy

javascriptfunctiondate

提问by Amra

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).

我正在尝试在 javascript 上创建一个函数,以格式 (yyyy-mm-dd) 从我的数据库中获取日期并将其显示为 (dd/mm/yy)。

I would appreciate any help.

我将不胜感激任何帮助。

Thanks.

谢谢。

PD: Let me know if you need more clarification.

PD:如果您需要更多说明,请告诉我。

回答by CMS

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

如果您确定来自服务器的日期有效,一个简单的 RegExp 可以帮助您更改格式:

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"

回答by Andy E

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"
}

回答by alemjerus

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

使用来自此来源的函数 getDateFromFormat() 和 formatDate():http://mattkruse.com/javascript/date/source.html
示例也有

回答by Ikai Lan

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

您可能还想考虑使用 date.js:

http://www.datejs.com

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.

为了使您的应用程序面向未来,您可能希望使用 JavaScript 以 UTC 时间戳和格式返回时间。这将允许您支持不同国家(在美国,我们最熟悉 DD-MM-YYYY 或实例)以及时区的不同格式。

回答by Faridul Khan

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"

回答by Anandan K

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

使用此 js 函数中的任何一个将日期 yyyy/mm/dd 转换为 dd/mm/yy

Type 1

类型 1

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

Type 2

类型 2

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

You can call those Functions by using :

您可以使用以下方法调用这些函数:

ChangeFormateDate("2018/12/17") //"17/12/2018"

回答by Hardik Pithva

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

您还可以使用解构和模板文字,以防您确定始终会收到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}`);

回答by bbsimonbb

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!

Date 对象就是为此设置的,一旦你掌握了它,它会让你走得更远。您的日期没有时区,因此我建议您在进出途中都强制使用 UTC。en-GB 语言环境强制使用 dd-mm,但您应该记住,说英语的用户在日期格式上分为中间部分,每一半都发现另一半的格式完全混乱。你真的应该尝试让你的数字日期格式适应用户的偏好,特别是因为它很容易!

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>