将模型中的日期时间更改为仅在C#web api中返回时间 [英] Change datetime in model to only return time only in C# web api

查看:174
本文介绍了将模型中的日期时间更改为仅在C#web api中返回时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HI全部,

我有这样的模型:



HI All,
I have a model like this:

public class Employees{

      public int Id {get;set;}
      public string Name {get;set;}
      public DateTime StartTime {get;set;}
      public DateTime FinishTime {get;set;}

}





然后我有一个webapi控制器返回搜索到的员工的详细信息,如下所示:





Then I have a webapi controller returning the details against a searched employee like this:

public class TimeController: ApiController
{
      [Route("api/getuserhours")]
        [HttpGet]
        public IEnumerable<Employees> GetDefaultTime()
        {
        
           var getEmp = context.Employees.Where(x => x.Name ==             currentUser).ToList();

         // now this is where i'm stuck .. i just want my model StartTime and //FinishTime  in particular to only return the time only not date. so how would i //access the getEmp here and change the datetime to return the time only .
           return getEmp;

   }


} 







所以在将结果发送到视图之前,我将如何将日期时间更改为仅返回时间?



谢谢。



我尝试了什么:



我正在跳这样访问getEmp:

getEmp.StartTime.TooString(设置时间在这里)但是nope这会引发错误




So before the results are sent to the view , how would i go about in changing the datetime to only return time?

Thank you .

What I have tried:

I was hopping to access the getEmp like this:
getEmp.StartTime.TooString("set time here") but nope this throws errors

推荐答案

DateTime不能只持有一段时间,线索在类名中:)



只需返回DateTime,你的视图可以在显示时将值转换为字符串,只是忽略日期部分,仅显示时间。
DateTime can't hold just a time, the clue is in the class name :)

Just return the DateTime as it is and your view can convert the value to a string when it shows it, just ignoring the date part and showing only the time.


var getEmp = context.Employees.Where(x => x.Name == currentUser).Select(x => new {Start = x.StartTime.ToString(HH:mm),Finish = x.FinishTime.ToString(HH:mm)})。AsEnumerable();



您还有其他选择:



DateTime dt = DateTime.Parse(6/22/2009 07:00:00 AM);



dt.ToString(HH:mm); // 07:00 // 24小时制//小时总是2位数

dt.ToString(hh:mm tt); // 07:00 AM // 12小时制//小时总是2位

dt.ToString(H:mm); // 7:00 // 24小时制

dt.ToString(h:mm tt); //上午7:00 // 12小时时间
var getEmp = context.Employees.Where(x=>x.Name == currentUser).Select(x=> new { Start = x.StartTime.ToString("HH:mm"),Finish = x.FinishTime.ToString("HH:mm") }).AsEnumerable();

You have other options also for this:

DateTime dt = DateTime.Parse("6/22/2009 07:00:00 AM");

dt.ToString("HH:mm"); // 07:00 // 24 hour clock // hour is always 2 digits
dt.ToString("hh:mm tt"); // 07:00 AM // 12 hour clock // hour is always 2 digits
dt.ToString("H:mm"); // 7:00 // 24 hour clock
dt.ToString("h:mm tt"); // 7:00 AM // 12 hour clock


这篇关于将模型中的日期时间更改为仅在C#web api中返回时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆