在 javascript 中打印 C# TimeSpan 值
Posted
技术标签:
【中文标题】在 javascript 中打印 C# TimeSpan 值【英文标题】:Print C# TimeSpan value in javascript 【发布时间】:2018-01-18 11:54:34 【问题描述】: var row = "";
jQuery.each(response.content, function (index, item)
row += "<tr ><td>" + item.lectureStartTime + " </td> </tr>";
);
$("#tbldialogfaculty***").html(row);
模型类
[Key]
[Column(Order = 9, TypeName = "time")]
[Required(ErrorMessage = "Required!")]
[DisplayName("Lecture Start Time")]
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "0:HH:mm tt")]
public TimeSpan lectureStartTime get; set;
[Key]
[Column(Order = 10, TypeName = "time")]
[Required(ErrorMessage = "Required!")]
[DisplayName("Lecture End Time")]
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "0:HH:mm tt")]
public TimeSpan lectureEndTime get; set;
[Column(Order = 11)]
[Required(ErrorMessage = "Required!")]
[DisplayName("lecture Total Duration")]
public long lectureTotalDuration get; set;
图片显示了数据库数据和结构
当我尝试使用 javascript 打印 lectureStartTime
时,它向我展示了 [object Object]
如何打印此 C# TimeSpan Object
我想打印10:00 AM
格式
【问题讨论】:
您需要使用浏览器的调试工具并在jQuery.each()
循环中设置断点。查看item.lectureStartTime
对象,看看它有哪些可用的键/值。
TimeSpan
是一个复杂的对象,需要根据它的属性来排列时间字符串,得到hh:mm tt格式。
@Pravin 我认为从控制器返回 JsonResult 时需要提供格式化字符串,并使用 DateTime
而不是 TimeSpan
。此参考可以帮助您返回 JSON 字符串:***.com/questions/14511709/….
@Pravin 您在这里有 2 个选择:将 TimeSpan
作为格式化的 JSON 字符串传递或传递 JSON 对象然后在 JS 中操作输出字符串(分别使用 lectureStartTime.Hours
和 lectureStartTime.Minutes
)。但我很困惑如何根据Hours
属性设置 AM/PM 字符串(可能变成 24 小时格式)。
(new Date(item.lectureStartTime.TotalMilliseconds)).toLocaleTimeString()
.
【参考方案1】:
你不应该这样做吗?
var row = "";
var time = item.lectureStartTime.Hours + " : " + item.lectureStartTime.Minutes + " : " + item.lectureStartTime.Seconds;
jQuery.each(response.content, function (index, item)
row += "<tr ><td>" + time + " </td> </tr>";
);
$("#tbldialogfaculty***").html(row);
由于 LectureStartTime 是一个复杂的对象,您必须自己构造字符串。
你也可以在你的模型中添加这样的属性
public string lectureStartTimeStr => $"lectureStartTime.Hours : lectureStartTime.Hours : lectureStartTime.Minutes";
编辑:在阅读了 cmets 之后,我改变了我的方法,我认为您正在寻找的是这样的(如果您选择在 ViewModel 中使用该属性)
public string lectureStartTimeStr => $"lectureStartTime:hh:mm:ss tt";
这样你的 Javascript 就可以了
var row = "";
jQuery.each(response.content, function (index, item)
row += "<tr ><td>" + item.lectureStartTimeStr + " </td> </tr>";
);
$("#tbldialogfaculty***").html(row);
【讨论】:
以上是关于在 javascript 中打印 C# TimeSpan 值的主要内容,如果未能解决你的问题,请参考以下文章