给定一个JavaScript Date对象实例,如何获得一个代表月份名称的字符串?
给定一个JavaScript Date对象实例,你怎样才能得到一个代表月份名称的字符串?
换句话说,从
我们怎样才能得到月份的名称呢?
每个Date对象实例都有一个toLocaleString() 方法,它是JavaScript国际化方法之一。
使用它,你可以得到你当前地区的月份名称,下面是你如何使用它。
const today = new Date()
today.toLocaleString('default', { month: 'long' })
根据你当前的语言环境,你会得到一个不同的结果。我得到的结果是 "十月"。
使用short 格式的日期,我得到 "Oct"。
today.toLocaleString('default', { month: 'short' })
第一个参数,我们把default 字符串传给它,是地区设置。你可以传递你想要的任何地区性,例如,it-IT 将返回你的ottobre 。
const today = new Date()
today.toLocaleString('it-IT', { month: 'long' })