在JS中将月份名称转换为月数的最简单的方式? (Jan = 01) [英] Easiest way to convert month name to month number in JS ? (Jan = 01)

查看:431
本文介绍了在JS中将月份名称转换为月数的最简单的方式? (Jan = 01)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只需要将一月隐藏到 01 (日期格式)

Just want to covert Jan to 01 (date format)

我可以使用 array(),但寻找另一种方式...

I can use array() but looking for another way...

任何建议?

推荐答案

只是为了这样做:

function getMonthFromString(mon){
   return new Date(Date.parse(mon +" 1, 2012")).getMonth()+1
}

奖金:它还支持完整的月份名称:-D
或者只是返回-1的新的改进版本 - 更改它以抛出异常(而不是返回) -1):

Bonus: it also supports full month names :-D Or the new improved version that simply returns -1 - change it to throw the exception if you want (instead of returning -1):

function getMonthFromString(mon){

   var d = Date.parse(mon + "1, 2012");
   if(!isNaN(d)){
      return new Date(d).getMonth() + 1;
   }
   return -1;
 }

为所有编辑进行调整 - 领先自己

Sry for all the edits - getting ahead of myself

这篇关于在JS中将月份名称转换为月数的最简单的方式? (Jan = 01)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆