简体   繁体   English

算法建议:如何查找最新日期(javascript)

[英]Algorithm avice: How to find the most recent date (javascript)

I am trying to add a function to my website that sorts through dates in formats like this "Apr 5, 2016, 5:56 PM" and figuring out if it is more recent than this "Apr 5, 2016, 9:56 AM" and by how long in (hours say). 我正在尝试向我的网站添加一个功能,该功能可以按“ 2016年4月5日,下午5:56”这样的格式对日期进行排序,并确定是否比“ 2016年4月5日,上午9:56”更新。以及多长时间(小时数)。 I know it would have to do with figuring out the month, then the year, then the hour and comparing them. 我知道这与确定月份,年份,小时然后比较它们有关。 Does anyone have any advice/samples on how to do this in javascript? 有人在javascript中有任何建议/示例吗? it is really bugging me? 真的在烦我吗?

Thanks 谢谢

You should always manually parse date strings, do not use Date.parse or the Date constructor (which are equivalent for parsing). 您应该始终手动解析日期字符串,不要使用Date.parse或Date构造函数(等效于解析)。 A library can help, but if you only have a single format, a bespoke function can do the job, eg 库可以提供帮助,但是如果您只有一种格式,则定制功能可以完成此任务,例如

 // Apr 5, 2016, 5:56 PM function parseDateString(s) { var months = {jan:0,feb:1,mar:2,apr:3,may:4,jun:5, jul:6,aug:7,sep:8,oct:9,nov:10,dec:11}; var b = s.match(/\\w+/g); var h = b[3]%12 + (/am/i.test(s)? 0 : 12); return new Date(b[2], months[b[0].toLowerCase()], b[1], h, b[4]); } var s = 'Apr 5, 2016, 5:56 PM'; document.write(parseDateString(s)); 

If you need a more general parser, there is moment.js but it may be way more than you need. 如果您需要更通用的解析器,则可以使用moment.js,但这可能超出您的需要。 If you just need a small parser and formatter, consider a utility like date-format.js or similar. 如果只需要一个小的解析器和格式化程序,请考虑使用诸如date-format.js之类的实用程序。

I think this might help you out: 我认为这可能会帮助您:

var date1 = new Date("7/13/2010");
var date2 = new Date("12/15/2010");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));

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

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