日期未正确转换

时间:2013-12-14 16:52:29

标签: php jquery

<?php
$file = fopen("admin/events/events.txt", "r");
while(!feof($file)){
    $line = fgets($file);
$result=htmlentities($line);
$s = $result;
preg_match_all('/data-day=\'([^\']*)\'/', $s, $matches);
foreach($matches[1] as $idx => $datevalue)
{
    $year = substr($datevalue, 0, 4);
    $month = substr($datevalue, 4, 2);
    $day = substr($datevalue, 6, 2);
}
$line = str_replace("<div data-role='day' data-day='$year$month$day", "<b><u>Datum:</b></u> $year-$month-$day ", $line);
$line = str_replace("'><div data-role='event' data-name='<h1>", " <br><b><u>Event:</b></u> ", $line);
$line = str_replace("' data-start='", " <br><b><u>Start:</b></u> ", $line);
$line = str_replace("' data-end='", " <br><b><u>Einde:</b></u> Tot ", $line);
$line = str_replace("' data-location='", " <br><b><u>Locatie:</b></u> ", $line);
$line = str_replace("</h1>", " <br><b><u>Inhoud event:</b></u><br> ", $line);
$line = str_replace("'></div></div>", "", $line);
echo "<div class='event'>$line</div>"; 
}
fclose($file);

?>

我使用此代码读出txt文件。然后显示事件。现在使用代码

转换YYYYMMDD格式的日期
$result=htmlentities($line);
$s = $result;
preg_match_all('/data-day=\'([^\']*)\'/', $s, $matches);
foreach($matches[1] as $idx => $datevalue)
{
    $year = substr($datevalue, 0, 4);
    $month = substr($datevalue, 4, 2);
    $day = substr($datevalue, 6, 2);
}

到YYYY-MM-DD格式。但有一个问题。对于像21031217或20141025,......或其他日期。日期转换正确。但有一些日期像201311,这意味着2013年1月第一次,但该代码转变为2013-11-所以这不是很好:)。因此,1-9和1-9天是单个数字,当日期转换为其他格式时会出现问题。有人能为我提供一些额外的代码来识别和转换正确的吗?

也许可以调整jquery代码?

我有一个jquery插件日历,用于读取certan日期的事件。现在它以YYYYMMDD的格式保存,现在一切正常,如20131225,20141022等日期,...代码也适用于201411的日期,这是2014年1月的第一个2014年6月是例如2014年第6个月第11天。现在我希望日期如20140101和20140611等等。有人可以编辑此代码。 THX

var yy;
var calendarArray =[];
var monthOffset = [6,7,8,9,10,11,0,1,2,3,4,5];
var monthArray = [["JAN","January"],["FEB","February"],["MAR","March"],["APR","April"],["MAY","May"],["JUN","June"],["JUL","July"],["AUG","August"],["SEP","September"],["OCT","October"],["NOV","November"],["DEC","December"]];
var dayArray = ["7","1","2","3","4","5","6"];
$(document).ready(function() {
    $(document).on('click','.calendar-day.have-events',activateDay);
    $(document).on('click','.specific-day',activatecalendar);
    $(document).on('click','.calendar-month-view-arrow',offsetcalendar);
    $(window).resize(calendarScale);
    calendarSet();
    calendarScale();
});

    function calendarScale() {
        $(".calendar").each(function() {
            if($(this).width() < 400 && !$(this).hasClass('small')) {
                $(this).addClass('small');
            } else if($(this).width() > 400 && $(this).hasClass('small')) {
                $(this).removeClass('small');
            }
        })
    }

    function offsetcalendar() {
        var cm = parseInt($(".calendar").attr('offset'));
        if($(this).data('dir') == "left") {
            calendarSetMonth(cm-1);
        } else if($(this).data('dir') == "right") {
            calendarSetMonth(cm+1);
        }

    }

    function orderBy(deli,array) {
        var p = array.slice();
        var o = p.length;
        var y,t;
        var temparray = [];
        for(var u=0; u<o;u++) {
            for(var uu=0;uu<p.length;uu++) {
                if(uu==0) {
                    t = uu;
                    y = p[uu];
                }
                else if(parseInt(p[uu][deli].replace('.','')) < parseInt(y[deli].replace('.',''))) {
                    y = p[uu];
                    t = uu;
                }
            }
            temparray.push(y);
            p.splice(t,1);
        }
        return temparray;
    }

    function calendarSet() {
        $(".calendar").append('<div class="calendar-month-view"><div class="calendar-month-view-arrow" data-dir="left">‹</div><p></p><div class="calendar-month-view-arrow" data-dir="right">›</div></div><div class="calendar-holder"><div class="calendar-grid"></div><div class="calendar-specific"><div class="specific-day"><div class="specific-day-info" i="day"></div><div class="specific-day-info" i="month"></div></div><div class="specific-day-scheme"></div></div></div>');
        $(".calendar").each(function() {
            if($(this).data("color") == undefined) {
                $(this).data("color","red");
            }
            $(this).find('[data-role=day]').each(function() {
                var tempdayarray = [];
                $(this).find('[data-role=event]').each(function() {
                    var tempeventarray = [];
                    tempeventarray["name"] = $(this).data("name");
                    tempeventarray["start"] = $(this).data("start");
                    tempeventarray["end"] = $(this).data("end");
                    tempeventarray["location"] = $(this).data("location");
                    tempdayarray.push(tempeventarray);
                });
                calendarArray[$(this).data('day')] = tempdayarray;
            });
        });
        $(".calendar [data-role=day]").remove();
        calendarSetMonth();
    }
    function activateDay() {
        $(this).parents('.calendar').addClass('spec-day');
        var di = new Date(parseInt($(this).attr('time')));
        var strtime = $(this).attr('strtime');
        var d = new Object();
        d.day = di.getDate();
        d.month = di.getMonth();
        d.events = calendarArray[strtime];
        d.tocalendar = tocalendar;
        d.tocalendar();
    }
    var tocalendar = function() {
        $(".specific-day-info[i=day]").html(this.day);
        $(".specific-day-info[i=month]").html(monthArray[this.month][0]);
        if(this.events !== undefined) {
        var ev = orderBy('start',this.events);
        for(var o = 0; o<ev.length;o++) {
            $(".specific-day-scheme").append('<div class="specific-day-scheme-event"><p>'+ev[o]['name']+'</p><p data-role="dur">'+ev[o]['start']+' - '+ev[o]['end']+'</p><p data-role="loc">'+ev[o]['location']+'</p></div>');
        }
        }
    }
    function activatecalendar() {
        $(this).parents('.calendar').removeClass('spec-day');
        $(".specific-day-scheme").html('');
    }
    function calendarSetMonth(offset) {
        $(".calendar-grid").html('');
        var d = new Date();
        var c = new Date();
        var e = new Date();
        if(offset !== undefined) {
            d.setMonth(d.getMonth()+offset);
            e.setMonth(e.getMonth()+offset);
            $(".calendar").attr('offset', offset);
        } else {
            $(".calendar").attr('offset', 0);
        }
        $(".calendar .calendar-month-view p").text(monthArray[d.getMonth()][1]+' '+d.getFullYear());
            d.setDate(1);
            if(dayArray[d.getDay()] == 1) {
                d.setDate(d.getDate()-7);
            } else {
                d.setDate(d.getDate()-dayArray[d.getDay()]+1);
            }
            for(var i=0;i<42;i++) {
                d.setDate(d.getDate()+i);
                var cal_day = $('<div class="calendar-day"><div class="date-holder">'+d.getDate()+'</div></div>');
                if(d.getMonth() !== e.getMonth()) {
                    cal_day.addClass('other-month');
                }
                if(d.getTime() == c.getTime()) {
                    cal_day.addClass('this-day');
                }
                var strtime = d.getFullYear()+''+(d.getMonth()+1)+''+d.getDate();
                if(calendarArray[strtime] !== undefined) {
                    cal_day.addClass('have-events');
                }
                var cal_day_eventholder = $('<div class="event-notif-holder"></div>');
                if(calendarArray[strtime] != undefined) {
                    for(var u=0;u<3 && u<calendarArray[strtime].length;u++) {
                        cal_day_eventholder.append('<div class="event-notif"></div>')
                    }
                }
                cal_day.attr('strtime',strtime);
                cal_day.attr('time',d.getTime());
                cal_day.prepend(cal_day_eventholder);

                $(".calendar-grid").append(cal_day);
                d.setDate(d.getDate()-i);
            }
    }

1 个答案:

答案 0 :(得分:0)

通过以非标准格式(YYYYmd)存储日期,此问题的任何解决方案都将使用对数据的任意解释。虽然它可能会在某些日期顺利进行,但总会有以错误的方式解释的日期,以及永远不会从逻辑上遵循任何字符串的日期。如果要解决此问题,只需 将格式更改为固定宽度格式(YYYYMMDD)。

虽然这可能不是您在问题的第一部分所期望的答案,“有人可以向我提供额外代码以识别和转换正确吗?”,我相信这是唯一正确的回答你问题的第二部分。


我不愿意通过100多行代码来查找您隐藏在哪里解释日期的部分,但如果您希望每个日期都有意义(ala看起来像日期),即使说日期可能不正确,您可以使用正则表达式来匹配日期:

var a = "201311";
var b = a.match(/^([0-9]{4})([01][012]|[0-9])([1-9][0-9]{0,1})$/);
console.log( b.slice(1).join("-") ); // 2013-1-1

然而,无法代表以下日期:

Expected "2013-1-11", got "2013-11-1" 
Expected "2013-1-12", got "2013-11-2" 
Expected "2013-1-13", got "2013-11-3" 
Expected "2013-1-14", got "2013-11-4" 
Expected "2013-1-15", got "2013-11-5" 
Expected "2013-1-16", got "2013-11-6" 
Expected "2013-1-17", got "2013-11-7" 
Expected "2013-1-18", got "2013-11-8" 
Expected "2013-1-19", got "2013-11-9" 
Expected "2013-1-21", got "2013-12-1" 
Expected "2013-1-22", got "2013-12-2" 
Expected "2013-1-23", got "2013-12-3" 
Expected "2013-1-24", got "2013-12-4" 
Expected "2013-1-25", got "2013-12-5" 
Expected "2013-1-26", got "2013-12-6" 
Expected "2013-1-27", got "2013-12-7" 
Expected "2013-1-28", got "2013-12-8" 
Expected "2013-1-29", got "2013-12-9"