Get Date from DateTime without ToShortDateString - c#

I am searching for this for about 2 hours and I don't have any ideas anymore.
The problem is I have a DateTime object and I need only the date part from it.
I tried
data.Date
create a new DateTime object like this
var x = new DateTime(data.Year,data.Months,data.Day)
I tried like this
DateTime.Parse(data.ToString("yyyy-MM-dd"))
NOTE: After getting the date part only, data needs to remain DateTime ( not string ), so I can not use ToShortDateString()

If you want some object, witch always return date in 2012-10-10 format from .ToString(), you can use this struct
struct Date
{
private DateTime dateTime;
public Date(DateTime dateTime)
{
this.dateTime = dateTime.Date;
}
public override string ToString()
{
return dateTime.ToString("yyyy-MM-dd");
}
}

Related

How to remove milliseconds and Culture Invariant?

I have a variable which is expiryDate from object product. The property of the expiry date is as below:
public DateTime? ExpiryDate{ get; set; }
The date is returned in the following format:
2020-01-15 11:16:40.6071922
Because my DateTime for ExpiryDate is nullable, when I try something like this:
var expiry = DateTime.ParseExact(products.ExpiryDate, "yyyy/MM/dd HH:mm:ss", null);
I get the below error:
CS8604 - Possible null reference argument for parameter 's' in DateTime DateTime.ParseExact...
I can suppress the error, but this is not what I want to do. Is there anyway to remove the milliseconds without having to convert to string.
To remove milliseconds you can do:
var expiry = products.ExpiryDate.AddMilliseconds(-products.ExpiryDate.Millisecond);
Generally, I use a static (extension) method like this
public static DateTime IgnoreTimeSpan(this DateTime dateTime, TimeSpan timeSpan)
{
if (timeSpan == TimeSpan.Zero)
return dateTime;
return dateTime.AddTicks(-(dateTime.Ticks % timeSpan.Ticks));
}
public static DateTime? IgnoreMilliseconds(this DateTime? dateTime)
{
if (!dateTime.HasValue) return dateTime;
return dateTime?.IgnoreTimeSpan(TimeSpan.FromMilliseconds(1000));
}
and call it like this
DateTime? input;
DateTime? output;
input = new DateTime(2019, 9, 9, 10, 10, 10, 765);
output = input.IgnoreMilliseconds(); // output = "09/09/2019 10:10:10"
This will support you to reuse it more than one time
You wrote:
The date is returned in the following format...
Apparently you have some method that returns a string representation of a DateTime.
If you want to convert a string to a DateTime is is usually better to use DateTime.Parse, instead of ParseExcact, because that will accept the text in several formats, even more if you use current culture as format provider.
In baby steps:
string dateTimeText = "2020-01-15 11:16:40.6071922";
DateTime dateTime = DateTime.Parse(dateTimeText, CultureInfo.CurrentCulture);
DateTime? nullableDateTime = dateTime;
If you expect that the text sometimes cannot be parsed;
DateTime? nullableDateTime;
if (DateTime.TryParse(dateTimeText, out DateTime dateTime))
{
// text could be parsed
nullableDateTime = dateTime;
}
else
{
nullableDateTime = null;
}
You can create a new DateTime.
This is necessary when you need to round more than one parameter.
var date = ExpiryDate.HasValue ?
(DateTime?) new DateTime(ExpiryDate.Value.Year, ExpiryDate.Value.Month,
ExpiryDate.Value.Day, ExpiryDate.Value.Hour, ExpiryDate.Value.Minute, ExpiryDate.Value.Second)
: null;

How to input a formatted date in a text box?

I'm confuse about how to make an input of formatted date time and currency. I want user to input the DoB as dd/mm/yyyy but when I'm using DateTime data type in Visual Studio it only get yyyy/mm/dd format.
Here's my code:
This is DoB and property from another class employee.cs
class employee
{
private DateTime myBOD;
public DateTime BOD
{
get
{
return myBOD;
}
set
{
myBOD = value;
}
}
}
This is the main form1.cs
vemployee.BOD = Convert.ToDateTime(bod.Text);
var today = DateTime.Today;
age.Text = Convert.ToString(today.Year-vemployee.BOD.Year);
Well, DateTime is a struct it doesn't have any format but properties like Year, Month, Day etc.
use DateTime.ParseExact when you want to obtain DateTime from string:
vemployee.BOD = DateTime.ParseExact(
bod.Text,
"dd'/'MM'/'yyyy", // Please, note that "mm" stands for minutes, not months
CultureInfo.InvariantCulture);
And .ToString(format) when you want to represent DateTime as a string
DateTime today = DateTime.Today;
bod.Text = today.ToString("dd'/'MM'/'yyyy", CultureInfo.InvariantCulture);

Convert string of date format to string of another date format

I want to convert a string of date format to a string with another format.
The string DateOfBirth could be in different formats such as:
01/15/2017
01-15-2017
1.15.2017
1.5.2017
I want to convert it to another pattern that I get it as parameter.
public string ConvertStringDateFormat(string date, string convertToDateFormat)
{
}
Let's assume that date = "01/15/2017" and convertToDateFormat = "YYYY/MM/DD". How could I change it to the new format?
The problem for me was to do it generic so that it will accept any parametrs.
I thought that I can convert date to DateTime and then to use ToString with the format but can you offer any better idea?
Parse to DateTime and then back to String:
public string ConvertStringDateFormat(string date, string convertToDateFormat) {
return DateTime
.ParseExact(date,
new string[] { "M/d/yyyy", "M-d-yyyy", "M.d.yyyy" },
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeLocal)
.ToString(convertToDateFormat); // convertToDateFormat = #"yyyy\/MM\/dd" for YYYY/MM/DD
}
i think this will work :
(Convert.ToDateTime(date)).ToString(convertToDateFormat)
try this
public string ConvertStringDateFormat(string date, string convertToDateFormat)
{
return Convert.ToString(Convert.ToDateTime(date),convertToDateFormat);
}

Failing when casting to DateTime object

I have this CSV
"06/04/2016 17:24:14,1443.92,0.31"
Which I try to convert into the following object
public class FooModel
{
public DateTime Date { get; set; }
public DateTime Time { get; set; }
public string Index { get; set; }
public string Change { get; set; }
}
with the following code
string[] values = line.Split(',');
FooModel m = new FooModel
{
Date = DateTime.ParseExact(values[0], "dd/MM/yyyy", CultureInfo.InvariantCulture),
Time = DateTime.ParseExact(values[0], "H:mm:ss", CultureInfo.InvariantCulture),
CultureInfo.InvariantCulture),
Index = values[1],
Change = values[2],
};
and failing on the exception
"String was not recognized as a valid DateTime."
How can I cast to DateTime Object
EDIT
I saw couple of answers that almost worked however it was my bad to mention that the date is formatted as Day-Month-Year. this means that it is failing when the csv is set to "22/12/2014 16:24:04,1476.83,-0.74"
I would guess the issue you're having is with the ParseExact part of this.
Why are you converting both the date and the time separately? It seems easier to do this:
DateTime Date = DateTime.Parse(values[0]);
string time = Date.ToLongTimeString();
string date = Date.ToLongDateString();
This way it's saved in the same variable and you can use the pieces as you need.
From the documentation:
The format of the string representation must match the specified format exactly.
The input string is:
"06/04/2016 17:24:14,1443.92,0.31"
The format string is:
"dd/MM/yyyy"
Those aren't really exact. Just use Parse instead:
Date = DateTime.Parse(values[0]);
This gives you the complete DateTime value, so you don't even need the Time property on the model. No need to store the same information twice, after all.
Additionally, you might use TryParse to be a little safer with the input:
DateTime temp;
if (!DateTime.TryParse(values[0], out temp))
{
// parsing error. notify the user?
}
Date = temp;
string[] s = "06/04/2016 17:24:14,1443.92,0.31".Split(',');
DateTime date = DateTime.Parse(s[0]);
This worked for me.
When you split the string values[0] = 06/04/2016 17:24:14 and you are parsing the Date and the Time component separately. Instead you need to parse them together with
DateTime date = DateTime.ParseExact(values[0], "dd/MM/yyyy H:mm:ss",
CultureInfo.InvariantCulture);
and access the date by
date.Date
and access the time by
date.Time

reverse timestamp

I was trying to save some stuff to the Log table with timestamp so I first did this:
public static string TimeStamp(
this DateTime datetime, string timestamptFormat = "yyyyMMddHHmmssffff")
{
return datetime.ToString(timestamptFormat);
}
And then I found a snippet like this:
static public string ToReverseTimestamp(this DateTime dateTime)
{
return string.Format("{0:10}", DateTime.MaxValue.Ticks - dateTime.Ticks);
}
I started wondering what the heck is reverse timestamp is useful for, and came across this article
Now my question is: if the second snippet is even correct? And how do you convert it back to "normal" timestamp or how do you get readable datetime information from it?
Make sure that the DateTime is converted to universal time before conversion to avoid time-zone problems:
public static string ToReverseTimestamp(this DateTime dateTime)
{
return (long.MaxValue - dateTime.ToUniversalTime().Ticks).ToString();
}
You can convert the value back to a DateTime value by parsing the string to a long, calculating MaxValue - (MaxValue - x) = x and constructing a new DateTime with DateTimeKind.Utc from x:
public static DateTime FromReverseTimestamp(string timestamp)
{
return new DateTime(long.MaxValue - long.Parse(timestamp), DateTimeKind.Utc);
}
Example:
var input = DateTime.Now; // {17/05/2012 16:03:17} (Local)
var timestamp = ToReverseTimestamp(input); // "2520650302020786038"
var result = FromReverseTimestamp(timestamp); // {17/05/2012 18:03:17} (Utc)

Categories

Resources