简体   繁体   English

从 Javascript 中的日期字符串中获取确切的日期

[英]Get exact day from date string in Javascript

I have checked this SO post: Where can I find documentation on formatting a date in JavaScript?我已经查看了这篇 SO 帖子: 我在哪里可以找到有关在 JavaScript 中格式化日期的文档?

Also I have looked into http://home.clara.net/shotover/datetest.htm我也调查了http://home.clara.net/shotover/datetest.htm

My string is: Mon Jun 24 2013 05:30:00 GMT+0530 (India Standard Time)我的字符串是: Mon Jun 24 2013 05:30:00 GMT+0530 (India Standard Time)

And I want to convert it to dd-mm-yyyy format.我想将其转换为dd-mm-yyyy格式。

I tried using:我尝试使用:

var dateString = 'Mon Jun 24 2013 05:30:00 GMT+0530 (India Standard Time)';
var myDate = new Date(dateString);
var final_date = myDate.getDay()+"-"+(myDate.getMonth()+1)+"-"+myDate.getFullYear();

But it gives me the result as: 1-6-2013但它给我的结果是: 1-6-2013

The getDay() value is the index of day in a week. getDay()值是一周中某天的索引。
For Instance, If my dateString is Thu Jun 20 2013 05:30:00 GMT+0530 (India Standard Time)例如,如果我的dateStringThu Jun 20 2013 05:30:00 GMT+0530 (India Standard Time)
it gives output as 4-6-2013它给出 output 作为4-6-2013

How can I get the proper value of Day?如何获得 Day 的正确值?

PS: I tried using .toLocaleString() and creating new date object from it. PS:我尝试使用.toLocaleString()并从中创建新日期 object。 But it gives the same result.但它给出了相同的结果。

要获取当月的日期,请使用getDate()

var final_date = myDate.getDate()+"-"+(myDate.getMonth()+1)+"-"+myDate.getFullYear();

W3 schools suggests just building your days of the week array and using it: W3学校建议您只需构建一周中的数组并使用它:

var d=new Date();
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";

var n = weekday[d.getDay()];

Not super elegant, but usable. 不是超级优雅,但可用。

var dateString = 'Mon Jun 24 2013 05:30:00 GMT+0530 (India Standard Time)';
var myDate = new Date(dateString);
var final_date = myDate.getDate()+"-"+(myDate.getMonth()+1)+"-"+myDate.getFullYear();

Replace getDay() with getDate(). 用getDate()替换getDay()。

The above will return the local date for each date part, use the UTC variants if you need the universal time. 以上将返回每个日期部分的本地日期,如果需要通用时间,请使用UTC变体。

我认为你必须使用getDay()方法中收到的索引来获取数天的时间并使用它。

To get required format with given date will achieve with moment.js.要获得具有给定日期的所需格式,将使用 moment.js 实现。 a one liner solution is一个线性解决方案是

import moment from "moment";

const date = new Date();
const finalDate = moment(date).format("DD-MM-YYYY")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM