簡體   English   中英

如何將日期和時間分開?

[英]How can I split date and time separate?

我在 mysql db 列中有一個 datetime 列,我需要在單獨的日期和時間文本框中顯示它。

我在 db 中的日期時間格式是2014-12-24 17:23:35 我想要:

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

我怎樣才能在 c# 中做到這一點?

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

您可以將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);

演示。

或者

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

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

數據庫中的日期時間沒有格式。 它以其本機二進制形式存儲。 如果您只需要顯示,因為沒有預期的更新,那么使用相同的數據庫列兩次,同時利用兩種字符串格式,一種僅用於日期部分,一種僅用於時間部分,例如在 .Net 應用程序中,您可以使用“ d”和“t”。

一些代碼給你:

<%@ 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

如果您使用任何 3rd 方控件,它們通常具有 Format 屬性,您可以在其中指定顯示所需的格式。

如果您已經有一個DateTime對象,這很簡單:

  • Date屬性只返回日期部分
  • TimeOfDay屬性只返回時間部分

如果您仍然遇到問題,我找到了一種簡單的方法。

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

如果您需要時間,只需使用第二個數組元素創建一個變量。

DateTime Date = DateTime.Parse(txtDate.Text).ToShortDateString(); // For Date
DateTime Date = DateTime.Parse(txtDate.Text).ToShortTimeString(); // for time
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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM