Skip to main content
 首页 » 编程设计

c#之尝试将日期转换为使用 .ToShortTimeString 以仅在我的 Web Api 中获取时间之无法正常工作

2024年04月30日39myhome

我试图仅从日期时间变量获取时间,但我遇到了一些困难。 我有一个这样的模型:

public class table{     
    public int Id {get;set;} 
    public string username {get; set;} 
    public DateTime DatePosted {get;set;}     
} 

然后我有一个这样的方法:

[HttpGet] 
public  IHttpActionResult GetPostedTime(){ 
    var gettime =  
        context.table.where(x => x.username == "some user") 
                     .select(x =>  
                        new { 
                            x.Id, 
                            x.username, 
                            x.DatePosted.ToshortTimeString() // try to get the time only here but getting        //error -  ​*anonymous type projection initializer should be simple name*​ 
                        }); 
    return gettime; 
} 

有没有更简单的方法我可以只从我的日期时间变量获取时间,或者我如何修复错误并只获取时间。 谢谢

请您参考如下方法:

您需要指定名称

var gettime = context.table.where(x => x.username == "some user").select(x => new { 
  Id = x.Id, 
  username = x.username, 
  DatePosted = x.DatePosted.ToshortTimeString()  
});