我正在向我发布的here发布一个后续问题,该问题已得到解决。
在我的应用程序中,我得到一个从输入表单(Gravity Forms List Field)上的动态字段中获取的值数组。可以通过以下方式创建具有相同结构的测试数组:
var entries = new Array();
entries[0] = new Array( 1, 1, 2016, "9:00", "am", "5:00", "pm");
entries[1] = new Array( 1, 2, 2016, "9:10", "am", "5:10", "pm");
从左到右,这些值为:月,日,年,开始时间,星期时间,结束时间,结束时间段。
由于它是动态输入 - 实际提交中可能有任意数量的子数组。
我的目标是拥有一组unix时间戳,我可以使用它来对表单提交进行验证。一个验证将是“当前日期超过上次提交日期的6个月”。
以下代码演示了我如何生成时间戳。
我正在寻找一种向我的数组添加无限数量时间戳的方法。
我也在寻找一种定位时间戳的方法,一旦我拥有它们。
// Create an array to collect timestamps
var sessions = new Array();
// Ready the Zero Prepend-er so dates are always correct
function twoDigitFormat( num ) {
return ( num.toString().length < 2 ? "0"+num : num ).toString();
}
// Loop through entries array to get each entry array
for ( i = 0; i < entries.length; i++ ) {
var entry = entries[i];
// Loop through each entry array to get the values
for ( j = 0; j < entry.length; j++ ) {
var value = entry[j];
// get all of the parts
var month = twoDigitFormat(entry[0]);
var day = twoDigitFormat(entry[1]);
var year = entry[2];
var stime = entry[3];
var stimeperiod = entry[4];
var etime = entry[5];
var etimeperiod = entry[6];
}
// Make Human Timestamps for each entry array
var sessionStartString = month+'-'+day+'-'+year+' '+stime+''+stimeperiod;
var sessionEndString = month+'-'+day+'-'+year+' '+etime+''+etimeperiod;
// I'm using moments.js for time handling
// Make Session Moments for each timestamp
var sStartMoment = moment( sessionStartString, "MM-DD-YYYY HH:mm a");
var sEndMoment = moment( sessionEndString, "MM-DD-YYYY HH:mm a");
// Make UNIX format moments for each timestamp
var sStartUnix = sStartMoment.unix();
var sEndUnix = sEndMoment.unix();
// Add each UNIX timestamp to the sessions array
// How do I add arrays with a variable as a key? I don't want to
// specify the key. Someone should be able to create 10 entries,
// or 20 entries, or .. whatever count.
sessions[0] = new Array ( sStartUnix );
sessions[1] = new Array ( sEndUnix );
}
// Get the current time (and as UNIX)
var now = moment();
var nowUnix = now.unix();
// Loop through sessions
for ( l = 0; l < sessions.length; l++ ) {
var session = sessions[l];
// How do I get things out of the array of timestamps?
// My current code results in session[key] being UNDEFINED?
var lastSession = session[session.length-1];
}
// Do stuff - like math, to run validations
// I know this isn't correct, but the idea will be to get
// a difference in hours
var lastNowDiff = nowUnix - lastSession;
if ( lastNowDiff > 4320 ) {
alert('The submission date must be within 6 months.');
}
如果你有时间检查一下,我有running in a Fiddle。
答案 0 :(得分:1)
使用数组的推送方法。
示例:
var entries = new Array();
entries.push(new Array( 1, 1, 2016, "9:00", "am", "5:00", "pm"));
你可以像这样添加任意数量的数组。
答案 1 :(得分:0)
使用JavaScript Date
对象进行解析和验证。