如何在ASP.Net中删除日期时间数据类型

Dan*_*ran 1 c# asp.net datetime

我有一个Datetime数据类型,12/30/2015 11:30:00 AM所以,在SQL服务器上,它将是fromDate.ToString ("yyyy-MM-dd HH: mm tt")结果2016-01-01 12: 30: 00,000,我想只在几天,几小时和几分钟内剪切字符串数据部分

Ian*_*Ian 7

改变你的

.ToString ("yyyy-MM-dd HH: mm tt") 
//showing: year (yyyy), month (MM), day of month (dd), hour (HH), minute (mm), and "The AM/PM designator" (tt)
Run Code Online (Sandbox Code Playgroud)

.ToString ("dd HH:mm")
//showing: day of month (dd), hour (HH), and minute (mm) only
Run Code Online (Sandbox Code Playgroud)

有关DateTime您可能觉得非常有用的格式的更多信息.使用方便的样品给出了解释并且非常完整.

编辑:

要解释此类文本数据SQL,请使用.Substring(int index, int length)

string text = sqltext.Substring(("2016-01-").Length, 9); //the 9 must be from your days to your minutes. If the text string is shorter/longer, change this value
Run Code Online (Sandbox Code Playgroud)

以下是两个Substring论点的解释:

  1. index参数从0文本的偏移开始.

    假设你的文字2016-01-01 12: 30: 00,000,然后index = 0将指向第一2,index = 1在第一0等等.要获取日期部分的第一个数字0,您需要7根据您的输入获得索引.但更简单的方法来确定index受回吐所有string 以前你想要的位置,并抓住它Length(这是我显示:"2016-01-").Length.

  2. length参数给出了您想要从index之后开始的字符数.

    因为你想要01 12: 30包含总数9字符(注意你的white spaces),你应该把它9.或者你也可以更通用("01 12: 30").Length:

    string text = sqltext.Substring(("2016-01-").Length, ("01 12: 30").Length);
    
    Run Code Online (Sandbox Code Playgroud)

詹姆斯先生的补充说明(见评论):"请注意,这个答案的"天数"是月份的日期,在任何情况下都不能超过31 ...如果你想要的天数来自一些基线日期,你必须做DateTime减法并使用a TimeSpan.ToString."