You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将JavaScript时间字符串转换为C# TimeSpan并传递至MVC方法

Converting JavaScript Time String to C# TimeSpan for MVC AJAX JSON Requests

Got it, let's break down how to make this work seamlessly—taking your JavaScript time string and getting it into a C# TimeSpan property via AJAX, while keeping types consistent and sticking to the hh:mm:ss format.

Frontend: Prepare the JSON Data

First, your JS time string var time = "10:15:00"; doesn't need any fancy conversion before sending it. The JSON serializer used by ASP.NET MVC (JSON.NET, by default) natively recognizes hh:mm:ss formatted strings as valid TimeSpan inputs. Just include it directly in your request payload:

// Build your request data
const payload = {
    Hours: time // Pass the "10:15:00" string directly
};

// Send the AJAX POST request
$.ajax({
    url: '/YourController/YourActionMethod',
    method: 'POST',
    contentType: 'application/json',
    data: JSON.stringify(payload),
    success: (response) => {
        // Handle success here
    },
    error: (xhr) => {
        // Handle errors if needed
    }
});

Pro tip: Add a quick regex check to ensure the time string is always in hh:mm:ss format before sending—this prevents binding errors on the backend:

const timeFormatRegex = /^([01]\d|2[0-3]):([0-5]\d):([0-5]\d)$/;
if (!timeFormatRegex.test(time)) {
    alert("Please enter a valid time in hh:mm:ss format");
    return; // Don't send the request if format is wrong
}

Backend: Receive and Bind to TimeSpan

Your existing C# property is already set up correctly:

public class YourViewModel
{
    public TimeSpan Hours { get; set; }
}

In your MVC controller action, just accept this view model as a parameter—ASP.NET will automatically bind the JSON string to the TimeSpan property:

[HttpPost]
public IActionResult YourActionMethod(YourViewModel model)
{
    // model.Hours is now a TimeSpan representing 10 hours, 15 minutes, 0 seconds
    // Do your business logic here

    return Json(new { success = true });
}

Keeping the hh:mm:ss Format for Display

If you need to send the TimeSpan back to the frontend for display, use the ToString method with a custom format to enforce hh:mm:ss:

string formattedTime = model.Hours.ToString("hh\\:mm\\:ss"); // Outputs "10:15:00"

Troubleshooting Notes

  • If you run into binding issues, double-check that your project is using JSON.NET (it's the default for most MVC setups). If not, you can configure it in your startup settings.
  • Avoid sending time strings with AM/PM notation—TimeSpan works with 24-hour format, so stick to hh:mm:ss (00-23 for hours).

内容的提问来源于stack exchange,提问作者Daniel Fellner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:00:43