更改日期字符串的格式 [英] Changing the format of a date string

查看:133
本文介绍了更改日期字符串的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个日期字符串 04-11-2010 ,在JavaScript中我希望有一个函数将它转换为 2010-11 -04

I have a date string, 04-11-2010, in JavaScript I want to have a function that will convert it to 2010-11-04.

有谁知道我怎么做?

推荐答案

JavaScript有一个字符串拆分函数,它将一个字符串分成一个部分数组。您可以使用 slice 只是砍掉字符串的部分:

JavaScript has a string split function, which separates a string into an array of parts. You can use slice to just chop up the parts of the string:

var str = "04-11-2010";

str = str.slice(-4) + "-" + str.slice(3, 5) + "-" + str.slice(0, 2);
alert(str);
//-> "2010-11-04"

另一个解决方案是拆分 - 字符上的字符串,交换周围的部分和重新加入

Another solution is to split the string on the - character, swap the parts around and rejoin it.

var str = "04-11-2010",
    // Split the string into an array
    arr = str.split("-"),
    // Store the value of the 0th array element
    tmp = arr[0];

// Swap the 0th and 2nd element of the array
arr[0] = arr[2];
arr[2] = tmp;

// Rejoin the array into our string
str = arr.join("-");

alert(str);
//-> 2010-11-04

这篇关于更改日期字符串的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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