我如何将日期和时间分开?

时间:2014-12-26 03:37:31

标签: c#

我在mysql db列中有一个datetime列,我需要在不同的日期和时间文本框中显示它。

我在db中的日期时间格式为2014-12-24 17:23:35。我想要:

Date : 2014-12-24  
Time : 17:23:35

我怎样才能在c#中做到?

7 个答案:

答案 0 :(得分:9)

DateTime dtValue;  // load your date & time into this variable
TextBox1.Text = dtValue.ToString("yyyy-MM-dd");
TextBox2.Text = dtValue.ToString("HH:mm:ss");

答案 1 :(得分:7)

您可以将datetime列检索为DateTime对象,然后将其格式化两次 - 一次使用忽略时间部分的格式,一次使用忽略日期部分的自定义格式。

var d = new DateTime(2014,12,26,17,21,30);
Console.WriteLine("Date: {0:d/M/yyyy} Time: {0:hh:mm:ss}", d);

Demo.

var d = new DateTime(2014,12,26,17,21,30);
var dtPart = d.ToShortDateString();
var tmPart = d.ToShortTimeString();

答案 2 :(得分:1)

  

我在db中的日期时间格式是2014-12-24 17:23:35

数据库中的日期时间没有格式。它以其原生二进制形式存储。如果您只需要显示(不是预期的更新),而不是使用相同的数据库列两次,同时利用两种字符串格式,一种仅用于日期部分,一种仅用于时间部分,例如你可以使用“d”和“t”的.Net应用程序。

一些代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>

<!DOCTYPE html>
<%
    var dateTimeColumnFromDatabase = DateTime.Now;
%>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <p>Date: <%= dateTimeColumnFromDatabase.ToString("d") %></p>
    <p>Time: <%= dateTimeColumnFromDatabase.ToString("t") %></p>

</body>
</html>

当然,您必须插入数据库代码来代替DateTime.Now

如果您使用任何第三方控件,它们通常具有Format属性,您可以在其中指定显示所需的格式。

答案 3 :(得分:0)

如果您已有DateTime个对象,这很简单:

  • Date属性只返回日期部分
  • TimeOfDay属性只返回时间部分

答案 4 :(得分:0)

DateTime Date = DateTime.Parse(txtDate.Text).ToShortDateString(); // For Date
DateTime Date = DateTime.Parse(txtDate.Text).ToShortTimeString(); // for time

答案 5 :(得分:0)

如果你仍然遇到麻烦,我找到了一种简单的方法。

    result= "7/26/2017 12:00:00 AM"; Whatever your variable is
    string[] Separate = result.Split (' ');
    string desiredDate = Separate [0];
    Debug.Log (desiredDate);

如果您需要时间,只需使用第二个数组元素创建一个变量。

答案 6 :(得分:0)

DateTime dt = DateTime.Now;               //Gets the current date
string datetime = dt.ToString();          //converts the datetime value to string
string[] DateTime = datetime.Split(' ');  //splitting the date from time with the help of space delimeter
string Date = DateTime[0];                //saving the date value from the string array
string Time = DateTime[1];                //saving the time value

**NOTE:** The value of the index position will vary depending on how the DateTime 
value is stored on your server or in your database if you're fetching from one.

Output: 10/16/2019 1:38:24 PM
        10/16/2019 1:38:24 PM
        ["10/16/2019","1:38:24","PM"]
        10/16/2019
        1:38:24
相关问题