我在Rails初始化程序中定义了以下日期格式:
Date::DATE_FORMATS[:default] = '%d/%m/%Y'
我想将此日期格式字符串(不是实际日期对象)传递给JavaScript-based datepicker widget。但是,datepicker只接受没有%
的格式字符串。例如,如果我将其传递给小部件,我需要将上面的日期格式字符串转换为dd/mm/YYYY
。
我可以进行转换的最简单方法是什么?还是有一种我甚至不需要的方式?
答案 0 :(得分:0)
这应该可以将您从数据采集器中选择的日期保存到数据库,因为它将使用日期轨道格式
$(".date-single-view").datepicker({
dateFormat: "yyyy-mm-dd"
});
答案 1 :(得分:0)
您可以使用strftime()方法
例如。d1.strftime('%d/%m/%Y');
有关详细信息,请查看此链接strftime
答案 2 :(得分:0)
使用支持函数替换的映射和正则表达式方法,可以最轻松地完成此类事情。
format
String. Default: “mm/dd/yyyy”
The date format, combination of d, dd, D, DD, m, mm, M, MM, yy, yyyy.
d, dd: Numeric date, no leading zero and leading zero, respectively. Eg, 5, 05.
D, DD: Abbreviated and full weekday names, respectively. Eg, Mon, Monday.
m, mm: Numeric month, no leading zero and leading zero, respectively. Eg, 7, 07.
M, MM: Abbreviated and full month names, respectively. Eg, Jan, January
yy, yyyy: 2- and 4-digit years, respectively. Eg, 12, 2012.
在Ruby中(请参阅strftime格式):
STRFTIME_TO_DATEPICKER = {
'-d' => 'd', # numeric date, no leading zero
'd' => 'dd', # numeric date, with leading zero
'a' => 'D', # abbreviated weekday name (e.g., Mon)
'A' => 'DD', # full weekday name (e.g., Monday)
'-m' => 'm', # numeric month, no leading zero
'm' => 'mm', # numeric month, with leading zero
'b' => 'M', # abbreviated month name (e.g., Jan)
'B' => 'MM', # full month name (e.g., January)
'y' => 'yy', # 2-digit year
'Y' => 'yyyy' # 4-digit year
}
puts '%d/%m/%Y'.gsub(/%(-?[dmyab])/i) { |match| STRFTIME_TO_DATEPICKER[$1] || match }
# => dd/mm/yyyy
puts '%d %-d %a %A %-m %m %b %B %y %Y %M %w'.gsub(/%(-?[dmyab])/i) { |match| STRFTIME_TO_DATEPICKER[$1] || match }
# => dd d D DD m mm M MM yy yyyy %M %w
在JavaScript中:
var convert_ruby_strftime_to_datepicker_format = (function () {
var format_conversions = {
'-d': 'd', // numeric date, no leading zero
'd' : 'dd', // numeric date, with leading zero
'a' : 'D', // abbreviated weekday name (e.g., Mon)
'A' : 'DD', // full weekday name (e.g., Monday)
'-m': 'm', // numeric month, no leading zero
'm' : 'mm', // numeric month, with leading zero
'b' : 'M', // abbreviated month name (e.g., Jan)
'B' : 'MM', // full month name (e.g., January)
'y' : 'yy', // 2-digit year
'Y' : 'yyyy' // 4-digit year
};
function convert_strftime(match, format) {
return format_conversions[format] || match;
}
return function (strftime) {
return strftime.replace(/%(-?[dmyab])/gi, convert_strftime);
};
})();
console.log(convert_ruby_strftime_to_datepicker_format('%d/%m/%Y'));
// dd/mm/yyyy
console.log(convert_ruby_strftime_to_datepicker_format('%d %-d %a %A %-m %m %b %B %y %Y %M %w'));
// dd d D DD m mm M MM yy yyyy %M %w
转换已知格式,并传递未知格式。