Ho bisogno di rimuovere la porzione di tempo di data o probabilmente la data nel seguente formato in forma di object
non sotto forma di string
.
06/26/2009 00:00:00:000
Non posso usare alcun metodo di conversione delle string
quanto ho bisogno della data in forma di object
.
Ho provato prima a convertire DateTime
in una string
, a rimuovere la data specifica dell’ora da esso, ma aggiunge 12:00:00 AM
non appena lo ricomincio object
DateTime
nuovamente.
Usa la proprietà Date :
var dateAndTime = DateTime.Now; var date = dateAndTime.Date;
La variabile della data conterrà la data, la parte dell’ora sarà 00:00:00
.
Puoi usare le stringhe di formato per dare alla stringa di output il formato che ti piace.
DateTime dateAndTime = DateTime.Now; Console.WriteLine(dateAndTime.ToString("dd/MM/yyyy")); // Will give you smth like 25/05/2011
Leggi di più qui .
Utilizzare il metodo ToShortDateString. Vedere la documentazione http://msdn.microsoft.com/en-us/library/system.datetime.toshortdatestring.aspx
var dateTimeNow = DateTime.Now; // Return 00/00/0000 00:00:00 var dateOnlyString = dateTimeNow.ToShortDateString(); //Return 00/00/0000
Dai un’occhiata alla proprietà DateTime.Date .
Ottiene il componente della data di questa istanza.
La proprietà Date
restituirà la data a mezzanotte.
Un’opzione potrebbe essere quella di ottenere i singoli valori (giorno / mese / anno) separatamente e memorizzarli nel tipo desiderato.
var dateAndTime = DateTime.Now; int year = dateAndTime.Year; int month = dateAndTime.Month; int day = dateAndTime.Day; string.Format("{0}/{1}/{2}", month, day, year);
Prova a creare la tua struttura per quello. L’object DateTime avrà data e ora entrambi
Non puoi Un DateTime in. NET ha sempre un tempo, predefinito a 00: 00: 00: 000. La proprietà Date di un DateTime è anche un DateTime (!), Quindi ha un tempo predefinito anche a 00: 00: 00: 000.
Questa è una carenza di .NET Framework e si potrebbe sostenere che DateTime in .NET viola il Principio di Responsabilità Unica .
Nessuna delle risposte precedenti ha risolto il mio problema su winforms.
il modo più semplice per raggiungere SOLO la data è la semplice funzione in Datetime:
DateTime dt = DateTime.now; String BirthDate = dt.ToShortDateString();
Avrai solo la data nella stringa Compleanno.
DateTime.Date
Questo modo di ottenere solo data senza tempo
DateTime date = DateTime.Now; string Strdateonly = date.ToString("d");
Risultato = 16/05/2015
Ecco un altro metodo che utilizza String.Format
DateTime todaysDate = DateTime.UtcNow; string dateString = String.Format("{0:dd/MM/yyyy}", todaysDate); Console.WriteLine("Date with Time: "+ todaysDate.ToString()); Console.WriteLine("Date Only : " + dateString);
Produzione:
Date with Time: 9/4/2016 11:42:16 AM Date Only : 04/09/2016
Questo funziona anche se l’ora della data è memorizzata nel database.
Per ulteriori formattazioni di data e ora, controllare questi collegamenti:
Riferimento 1
Riferimento 2
La speranza aiuta
Sono sorpreso che nessuno abbia menzionato DateTime.Today
var date = DateTime.Today; // {7/1/2014 12:00:00 AM}
Vedi MSDN
È venuto attraverso questo post quando cercavo di risolvere la Q originale.
Sto usando Asp.Net e dopo alcune ricerche che ho trovato quando si sta legando il valore della data nel codice, è ansible rilasciare il tempo in modo che non venga visualizzato sullo schermo.
C #:
DateTime Today = DateTime.Now;
aspx:
<%: this.Today.ToShortDateString() %>
uso
DateTime.Now.ToString("dd-MM-yyyy");
Ho scritto una struttura DateOnly
. Questo utilizza un DateTime sotto la pelle, ma in nessun momento le parti sono esposte pubblicamente:
using System; public struct DateOnly : IComparable, IFormattable, IComparable, IEquatable { private DateTime _dateValue; public int CompareTo(object obj) { if (obj == null) { return 1; } DateOnly otherDateOnly = (DateOnly)obj; if (otherDateOnly != null) { return ToDateTime().CompareTo(otherDateOnly.ToDateTime()); } else { throw new ArgumentException("Object is not a DateOnly"); } } int IComparable .CompareTo(DateOnly other) { return this.CompareToOfT(other); } public int CompareToOfT(DateOnly other) { // If other is not a valid object reference, this instance is greater. if (other == new DateOnly()) { return 1; } return this.ToDateTime().CompareTo(other.ToDateTime()); } bool IEquatable .Equals(DateOnly other) { return this.EqualsOfT(other); } public bool EqualsOfT(DateOnly other) { if (other == new DateOnly()) { return false; } if (this.Year == other.Year && this.Month == other.Month && this.Day == other.Day) { return true; } else { return false; } } public static DateOnly Now() { return new DateOnly(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day); } public static bool TryParse(string s, ref DateOnly result) { DateTime dateValue = default(DateTime); if (DateTime.TryParse(s, out dateValue)) { result = new DateOnly(dateValue.Year, dateValue.Month, dateValue.Day); return true; } else { return false; } } public static DateOnly Parse(string s) { DateTime dateValue = default(DateTime); dateValue = DateTime.Parse(s); return new DateOnly(dateValue.Year, dateValue.Month, dateValue.Day); } public static DateOnly ParseExact(string s, string format) { CultureInfo provider = CultureInfo.InvariantCulture; DateTime dateValue = default(DateTime); dateValue = DateTime.ParseExact(s, format, provider); return new DateOnly(dateValue.Year, dateValue.Month, dateValue.Day); } public DateOnly(int yearValue, int monthValue, int dayValue) : this() { Year = yearValue; Month = monthValue; Day = dayValue; } public DateOnly AddDays(double value) { DateTime d = new DateTime(this.Year, this.Month, this.Day); d = d.AddDays(value); return new DateOnly(d.Year, d.Month, d.Day); } public DateOnly AddMonths(int months) { DateTime d = new DateTime(this.Year, this.Month, this.Day); d = d.AddMonths(months); return new DateOnly(d.Year, d.Month, d.Day); } public DateOnly AddYears(int years) { DateTime d = new DateTime(this.Year, this.Month, this.Day); d = d.AddYears(years); return new DateOnly(d.Year, d.Month, d.Day); } public DayOfWeek DayOfWeek { get { return _dateValue.DayOfWeek; } } public DateTime ToDateTime() { return _dateValue; } public int Year { get { return _dateValue.Year; } set { _dateValue = new DateTime(value, Month, Day); } } public int Month { get { return _dateValue.Month; } set { _dateValue = new DateTime(Year, value, Day); } } public int Day { get { return _dateValue.Day; } set { _dateValue = new DateTime(Year, Month, value); } } public static bool operator == (DateOnly aDateOnly1, DateOnly aDateOnly2) { return (aDateOnly1.ToDateTime() == aDateOnly2.ToDateTime()); } public static bool operator != (DateOnly aDateOnly1, DateOnly aDateOnly2) { return (aDateOnly1.ToDateTime() != aDateOnly2.ToDateTime()); } public static bool operator > (DateOnly aDateOnly1, DateOnly aDateOnly2) { return (aDateOnly1.ToDateTime() > aDateOnly2.ToDateTime()); } public static bool operator < (DateOnly aDateOnly1, DateOnly aDateOnly2) { return (aDateOnly1.ToDateTime() < aDateOnly2.ToDateTime()); } public static bool operator >= (DateOnly aDateOnly1, DateOnly aDateOnly2) { return (aDateOnly1.ToDateTime() >= aDateOnly2.ToDateTime()); } public static bool operator <= (DateOnly aDateOnly1, DateOnly aDateOnly2) { return (aDateOnly1.ToDateTime() <= aDateOnly2.ToDateTime()); } public static TimeSpan operator - (DateOnly aDateOnly1, DateOnly aDateOnly2) { return (aDateOnly1.ToDateTime() - aDateOnly2.ToDateTime()); } public override string ToString() { return _dateValue.ToShortDateString(); } public string ToString(string format) { return _dateValue.ToString(format); } public string ToString(string fmt, IFormatProvider provider) { return string.Format("{0:" + fmt + "}", _dateValue); } public string ToShortDateString() { return _dateValue.ToShortDateString(); } public string ToDbFormat() { return string.Format("{0:yyyy-MM-dd}", _dateValue); } }
Questo viene convertito da VB.NET, quindi scuse se alcune conversioni non sono al 100%
string dt = myCalender.SelectedDate.ToString(); string date = dt.Remove(10); displayDate.Content = date;
Se prendi una data dal calendario, con questo otteniamo anche il tempo. Quale non è richiesto sempre. Usando questo possiamo rimuovere il tempo dalla data.
nella mia esperienza nessuna delle suddette soluzioni ha funzionato, forse perché volevo rimuovere il tempo dalla data estratta dal database, ma il codice sottostante funzionava bene:
var date = target_date.Value.ToString("dd/MM/yyyy");
È ansible provare questo per la sola data dal datetime
String.Format("{0:d/M/YYYY}",dt);
Dove dt è il DateTime
Dichiarare la variabile come una stringa.
esempio :
public string dateOfBirth ;
quindi assegna un valore come:
dateOfBirth = ((DateTime)(datetimevaluefromDB)).ToShortDateString();
Se lo converti in stringa, puoi farlo facilmente in questo modo.
Sto prendendo la data come object DateTime.
date.ToString("d");
Questo ti darà solo la data.
So che questo è un vecchio post con molte risposte, ma non ho visto questo modo di rimuovere la parte del tempo. Supponiamo che tu abbia una variabile DateTime
chiamata myDate
, con la parte data con time. Puoi creare un nuovo object DateTime
da esso, senza la parte time, usando questo costruttore:
public DateTime(int year, int month, int day);
Come questo:
myDate = new DateTime(myDate.Year, myDate.Month, myDate.Day);
In questo modo crei un nuovo object DateTime
basato su quello vecchio, con 00:00:00 come parte del tempo.
Crea una struttura che contiene solo le proprietà che desideri. Quindi un metodo di estensione per ottenere facilmente tale struttura da un’istanza di DateTime.
public struct DateOnly { public int Day { get; set; } public int Month { get; set; } public int Year { get; set; } } public static class DateOnlyExtensions { public static DateOnly GetDateOnly(this DateTime dt) { return new DateOnly { Day = dt.Day, Month = dt.Month, Year = dt.Year }; } }
uso
DateTime dt = DateTime.Now; DateOnly result = dt.GetDateOnly();
Usa. L’indicazione di un object DateTime ignorerà la parte relativa all’ora.
Ecco il codice:
DateTime dateA = DateTime.Now; DateTime dateB = DateTime.Now.AddHours(1).AddMinutes(10).AddSeconds(14); Console.WriteLine("Date A: {0}",dateA.ToString("o")); Console.WriteLine("Date B: {0}", dateB.ToString("o")); Console.WriteLine(String.Format("Comparing objects A==B? {0}", dateA.Equals(dateB))); Console.WriteLine(String.Format("Comparing ONLY Date property A==B? {0}", dateA.Date.Equals(dateB.Date))); Console.ReadLine();
Produzione:
>Date A: 2014-09-04T07:53:14.6404013+02:00 >Date B: 2014-09-04T09:03:28.6414014+02:00 >Comparing objects A==B? False >Comparing ONLY Date property A==B? True
Usa un po ‘di RegEx:
Regex.Match(Date.Now.ToString(), @"^.*?(?= )");
Produce una data nel formato: gg / mm / aaaa
Per l’utilizzo da parte del datalist, ripetitore .. nella pagina aspx: <% # Eval ("YourDateString"). ToString (). Remove (10)%>
Questo potrebbe essere fatto semplicemente in questo modo:
var dateOnly = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day)
Ottenere la parte Date
di un object DateTime
non ha funzionato per me perché sto lavorando sul lato client e i valori del servizio web restituito hanno alcune date null
. Di conseguenza, tenta di ottenere la parte Data di un valore nullo e genera un’eccezione di runtime. Il seguente esempio è come ho risolto il mio problema:
string dt = employer.BirthDay.ToString(); if(dt == ""){ dt = "N/A";} else dt = dt.Substring(0,10);
DateTime
della stringa e assegnarlo alla variabile stringa. Sto condividendo questo per riferimento futuro.
DateTime dd=DateTiem.Now; string date=dd.toString("dd/MM/YYYY");
static void Main(string[] args) { string dateStrings = "2014-09-01T03:00:00+00:00" ; DateTime convertedDate = DateTime.Parse(dateStrings); Console.WriteLine(" {0} ----------------- {1}", convertedDate,DateTime.Parse(convertedDate.ToString()).ToString("dd/MM/yyyy")); Console.Read(); }
Questo codice offre una visione chiara della Date
e del Time
separatamente
string time = DateTime.Now.Hour.ToString("00") + ":" + DateTime.Now.Minute.ToString("00") + ":" + DateTime.Now.Second.ToString("00"); string date = DateTime.Now.ToString("M-dd-yyyy"); MessageBox.Show(date + "\n" + time);
Spero che questo ti aiuti.