当发送到MVC控制器时,如何将JavaScript字符串“5:00 PM”转换为DateTime或TimeSpan。我正在使用
自举-timepicker
// usage
<script type="text/javascript">
$('#timepicker1').timepicker();
</script>
Javascript有效负载
{
Skip: 0
Status: []
Take: 15
DueTime: "1:00 PM" // keep in mind that this is a string
}
服务器对象类似于
class TimeSheet
{
public TimeSpan DueTime;
}
答案 0 :(得分:2)
使用DateTime.Parse
。当您的字符串随时间传输时,在服务器(在控制器上)转换。
http://msdn.microsoft.com/ru-ru/library/system.datetime.parse(v=vs.110).aspx
答案 1 :(得分:0)
好吧所以我读了所有错误因此删除的答案..!
但我不放弃;)
你的bootstrap-timepicker会给你一个时间,因为这是“下午1点”。
但在此之前,我们将在服务器端查看我们可以解析为datetime对象的内容。
这是解析日期时间的C#。
string dateString, format;
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
dateString = "15/08/2000 16:58"
format = "dd/MM/yyyy HH:mm"
result = DateTime.ParseExact(dateString, format, provider);
现在你的字符串看起来不像我会假设你想要今天的日期!
这是我倾向于在转换时大部分时间使用的功能,到24小时。
function ConvertTimeformat(str) {
var time = str;
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if (AMPM == "PM" && hours < 12) hours = hours + 12;
if (AMPM == "AM" && hours == 12) hours = hours - 12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if (hours < 10) sHours = "0" + sHours;
if (minutes < 10) sMinutes = "0" + sMinutes;
//Creating the todays date in the right format
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;//January is 0!`
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd}
if(mm<10){mm='0'+mm}
var todaysdate = dd+'/'+mm+'/'+yyyy +" " ; //<--I added an extra space!
var hoursNminutes = sHours + ":" + sMinutes
//CREATE THE RIGHT FORMAT FOR DATE.PARSEXACT "dd/MM/yyyy HH:mm"
var dateToParse = todaysdate + hoursNminutes
return dateToParse;
}
要使用此功能,请执行此操作!
//Call it and provide your bootstrap time. And make it return to a variable
var dateToBeSentToServer = ConvertTimeformat("1:00 PM");
//OR With the bootstraptime as a variable
var dateToBeSentToServer = ConvertTimeformat(timevariable);
现在您可以将dateToBeSentToServer发送到服务器端进行解析!