Javascript:从字符串中提取日期?
我有一个字符串格式为
Today 3:28AM
Yesterday 3:28AM
08/22/2011 3:28AM
我需要做的是以某种方式将字符串的日期部分提取到变量中,即。 “今天”、“昨天”或格式为 DD/MM/YYYY 的日期。
Javascript 可能实现这样的事情吗?
I have a string formatted as either
Today 3:28AM
Yesterday 3:28AM
08/22/2011 3:28AM
What I need to do is somehow extract into a variable the date portion of my string, ie. 'Today', 'Yesterday' or a date formatted as DD/MM/YYYY.
Is something like this possible at all with Javascript?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
由于 JavaScript 日期解析器无法识别您的日期,因此您可以编写一个解析器,将日期转换为它可以识别的格式。下面是一个函数,它采用您提供的日期示例并格式化它们以获得有效的日期字符串:
然后您可以调用 stroToDate 将日期格式转换为有效的 JavaScript 日期:
输出:
Since the JavaScript date parser won't recognize your dates, you can write a parser that puts the date into a format that it will recognize. Here is a function that takes the date examples that you gave and formats them to get a valid date string:
Then you can call stroToDate to convert your date formats to a valid JavaScript Date:
Outputs:
显然“今天”和“昨天”永远无法转换回真正的数字日期,目前看来您在这里要做的就是将其保存为“今天”和“昨天”,对吧?
您指定的 dd/mm/yyyy hh:mmxx 似乎始终以空格分隔。
所以你可以将字符串分成两部分,并将第一部分保存为日期。
JavaScript 函数:
http://www.w3schools.com/jsref/jsref_split.asp
至于如何从“今天”转换回26/09/2011等,您需要从XML方面寻求解决方案。
Obviously "Today" and "Yesterday" can never be transformed back to a real numeric date, for now it seems that what are you trying to do here is to save it as "Today" and "Yesterday", right?
It appears that the dd/mm/yyyy hh:mmxx you specified is always separated by a space.
so you can just split the string into two, and save the first part as your date.
the javascript function:
http://www.w3schools.com/jsref/jsref_split.asp
As for how to transform from "Today" back to 26/09/2011 etc, you need to seek solution from the XML side.
这是一个类似的问题:Javascript相当于php的strtotime()?
这里是链接的文章: http://w3schools.com/jS/js_obj_date.asp
以及建议的解决方案:
Here is a similar question: Javascript equivalent of php's strtotime()?
Here is the linked article: http://w3schools.com/jS/js_obj_date.asp
And the suggested solution:
有几种方法可以做到这一点。我将提供其中 2 个。
选项1:
如果日期始终位于字符串的开头,则可以使用
/([a-z0-9]*)\s|([0-9]{1,} 等正则表达式捕获第一部分)\/([0-9]{1,})\/([0-9]{1,})\s/
<- 我不是最好的正则表达式编写者。选项2:
如果时间在一天之后立即到来,您也可以进行积极的展望(就像上面的示例一样。这里是 JS 正则表达式的正确语法的链接。http://www.javascriptkit.com/javatutors/redev2.shtml 您可以向下滚动到前瞻并查看一个示例,应该可以让您顺利离开那里。
There are a couple of ways you could do this. I will offer 2 of them.
option1:
If the day always at the beginning of the string you could capture the the first part by using a regular expression like
/([a-z0-9]*)\s|([0-9]{1,})\/([0-9]{1,})\/([0-9]{1,})\s/
<- im not the best regex writer.option2:
You could also do a positive look ahead if the time come immediately after the day (like your example above. Here is a link with the proper syntax for JS regex. http://www.javascriptkit.com/javatutors/redev2.shtml you can scroll down to lookaheads and see an example that should get you suared away there.