在 Javascript 中将字符串转换为日期以返回 JSON 数组

发布于 2024-12-01 16:53:59 字数 323 浏览 1 评论 0原文

我想将字符串转换为日期对象,并添加该日期的最后三个月,以使用 javascript 形成季度报告。

例如,我使用以下命令收到以下字符串“August-2010”

var currDate = "August-2010";

根据日期,我需要计算从当前日期算起的最后三个月,例如: 2010年7月 2010年6月 2010 年 5 月

最后,我需要将结果格式化为以下格式的数组:

[May,Jun,Jul,Aug];

我应该如何在 Javascript 中执行此操作?

I would like to convert a string to date object and add in the last three month from the date to form a quarterly report using javascript.

For example, I am receiving the following string "August-2010" using the following

var currDate = "August-2010";

Based on the date, I will need to compute the last three months from the current date, for example:
July-2010
June-2010
May-2010

Lastly, I will need to format that result into an array in the following format:

[May,Jun,Jul,Aug];

How should I do it in Javascript?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

我只土不豪 2024-12-08 16:54:00

如果 currDate 的格式是固定的,我想你将不得不处理你的字符串并放置一些 if 和 else 以获得最终结果。例如,

<script type="text/javascript">
    var monthArray = ["January","February","March","April","May","June","July","September","October","November","December"];
    var currDate = "August-2010";
    var month = currDate.substring(0,currDate.indexOf("-"));
    var year  = parseInt(currDate.substr(currDate.indexOf("-")+1));
    int i;
    for (i = 0 ; i < 12 ; i++) {
        if (month == monthArray[i]) break;
    }
    var resultArray = []; //This is the array that contain 4 months
    resultArray[3] = month.substring(0,3); //The last element of the array should be the month in currDate, I suppose the format is the 1st 3 letters of the month

    for (int j = 1 ; j < 4 ; j++) {
        var theYear = year;
        var k = i - j;
        if (k < 0) {
            k+=12;
            theYear--;
        }
        var theMonth = monthArray[k];
        resultArray[3-i] = theMonth.substring(0,3);
        alert(theMonth+"-"+theYear); // You get the 3 previous month here (e.g. July-2010, etc...)
    }

</script> 

If the format for currDate is fixed, I guess you will have to process your string and put a number of if and else to get the final result. For example,

<script type="text/javascript">
    var monthArray = ["January","February","March","April","May","June","July","September","October","November","December"];
    var currDate = "August-2010";
    var month = currDate.substring(0,currDate.indexOf("-"));
    var year  = parseInt(currDate.substr(currDate.indexOf("-")+1));
    int i;
    for (i = 0 ; i < 12 ; i++) {
        if (month == monthArray[i]) break;
    }
    var resultArray = []; //This is the array that contain 4 months
    resultArray[3] = month.substring(0,3); //The last element of the array should be the month in currDate, I suppose the format is the 1st 3 letters of the month

    for (int j = 1 ; j < 4 ; j++) {
        var theYear = year;
        var k = i - j;
        if (k < 0) {
            k+=12;
            theYear--;
        }
        var theMonth = monthArray[k];
        resultArray[3-i] = theMonth.substring(0,3);
        alert(theMonth+"-"+theYear); // You get the 3 previous month here (e.g. July-2010, etc...)
    }

</script> 
薄荷港 2024-12-08 16:54:00
var getLastThreeMonths = (function(){

    var months = [
            'Jan','Feb','Mar','Apr','May','Jun',
            'Jul','Aug','Sep','Oct','Nov','Dec'
        ],
        monthsAsObj = (function() {
            var r = {}, l = 12;
            while (l--) r[months[l]] = l;
            return r;
        }());

    return function getLastThreeMonths(date){

        var month = date.split('-')[0],
            monthIndex = monthsAsObj[month.slice(0,3)];

        return months.slice(monthIndex - 3, monthIndex);

    };

}());

getLastThreeMonths('August-2010'); // => ["May", "Jun", "Jul"]
var getLastThreeMonths = (function(){

    var months = [
            'Jan','Feb','Mar','Apr','May','Jun',
            'Jul','Aug','Sep','Oct','Nov','Dec'
        ],
        monthsAsObj = (function() {
            var r = {}, l = 12;
            while (l--) r[months[l]] = l;
            return r;
        }());

    return function getLastThreeMonths(date){

        var month = date.split('-')[0],
            monthIndex = monthsAsObj[month.slice(0,3)];

        return months.slice(monthIndex - 3, monthIndex);

    };

}());

getLastThreeMonths('August-2010'); // => ["May", "Jun", "Jul"]
秋心╮凉 2024-12-08 16:54:00
var searched, iFound, res, months = [ 'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec' ];
var currDate = "August-2010";

// IE does not implement Arrays' indexOf, here is a workaround :
if(!Array.prototype.indexOf){
   Array.prototype.indexOf = function(expected){
     for(var i = 0; i < this.length; i++){
        if(this[i] === expected) return i;
     }
     return -1;
   }
}

searched = currDate.substring(0,3); // lets take the only 3 first letters of currDate
iFound = months.indexOf(searched); // we look for the index of the month in the array
if(iFound >= 0){ // if the month was found
   res = months.slice(iFound-3, iFound+1); // slice copies a portion of the array. Here, it copies from iFound-3 to iFound+1 (excluded)
   console.log(res);
}
var searched, iFound, res, months = [ 'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec' ];
var currDate = "August-2010";

// IE does not implement Arrays' indexOf, here is a workaround :
if(!Array.prototype.indexOf){
   Array.prototype.indexOf = function(expected){
     for(var i = 0; i < this.length; i++){
        if(this[i] === expected) return i;
     }
     return -1;
   }
}

searched = currDate.substring(0,3); // lets take the only 3 first letters of currDate
iFound = months.indexOf(searched); // we look for the index of the month in the array
if(iFound >= 0){ // if the month was found
   res = months.slice(iFound-3, iFound+1); // slice copies a portion of the array. Here, it copies from iFound-3 to iFound+1 (excluded)
   console.log(res);
}
小兔几 2024-12-08 16:53:59

此函数返回最近 X 个月的月+年:

function getPastXMonths(theDate, X) {

    var d = new Date(Date.parse(theDate.replace('-', ' 1 ')));
    var out = [];
    var i = 0;

    while (i++ < X) {
        out.push([
        'January','February','March','April','May','June','July','August','September','October','November','December'
        ][d.getMonth()] + '-' + d.getFullYear());
        d.setMonth(d.getMonth() - 1);
    }

    return out;
}

var months = getPastXMonths('August-2010', 3);
alert(months.join('\n'));

http://jsfiddle.net/SLcNJ/4/< /a>

This function returns the month+year of the last X months:

function getPastXMonths(theDate, X) {

    var d = new Date(Date.parse(theDate.replace('-', ' 1 ')));
    var out = [];
    var i = 0;

    while (i++ < X) {
        out.push([
        'January','February','March','April','May','June','July','August','September','October','November','December'
        ][d.getMonth()] + '-' + d.getFullYear());
        d.setMonth(d.getMonth() - 1);
    }

    return out;
}

var months = getPastXMonths('August-2010', 3);
alert(months.join('\n'));

http://jsfiddle.net/SLcNJ/4/

倾城泪 2024-12-08 16:53:59
var Months = ["Jan", "Feb", "Mar", "Apr", "May", "June", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

var d = new Date(Date.parse("August-2010"));
var CurrentMonth = d.getMonth();
var NumberOfMonthsBack = 4;
var Quarter = [];

for(x = 0; x < NumberOfMonthsBack; x++) {
    if(CurrentMonth == -1) {
        CurrentMonth = 11;
    }
    Quarter.unshift(Months[CurrentMonth--]);
}

alert(Quarter);
var Months = ["Jan", "Feb", "Mar", "Apr", "May", "June", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

var d = new Date(Date.parse("August-2010"));
var CurrentMonth = d.getMonth();
var NumberOfMonthsBack = 4;
var Quarter = [];

for(x = 0; x < NumberOfMonthsBack; x++) {
    if(CurrentMonth == -1) {
        CurrentMonth = 11;
    }
    Quarter.unshift(Months[CurrentMonth--]);
}

alert(Quarter);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文