How to remove milliseconds and Culture Invariant? - c#

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;

Related

formatting Datetime string

i have the following object that can be nullable at times follows
public string issued {get;set;}
The issued string looks like this: 2022/02/29 22:00:00 +00:00
I want to assign the issued variable to another variable as 2022/02/29 when its not null.
This is what i tried:
var item = new model() {
issuedDate=issued.IsNullOrEmpty() ? "" : issued.ToString("yyyy/mm/dd")
}
But it throws an error:
can not convert from string to system.IformatProvider?
How can I fix this?
I recommend using DateTime as helper with TryParseExact to determine if the source is a valid DateTime format. Via the DateTime helper variable you can then create any DateTime formatted strings you need to.
string issued = #"2022/02/29 22:00:00 +00:00";
string issuedDate;
DateTime dateTimeIssued;
if (DateTime.TryParseExact(issued, "yyyy/MM/dd HH:mm:ss zzz", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTimeIssued)) {
issuedDate = dateTimeIssued.ToString("yyyy/MM/dd");
}
Be aware that TryParseExact only works if the format is known to the system culture.
you can try for format;
string.Format("{0:yyyy/MM/dd}",issued);
this will be return 2022/02/29 for you
and you can look this page, for more information on DateTime format.
https://www.csharp-examples.net/string-format-datetime/

Getting date in correct formatted for with proper timezone, among list of strings in an a array

I have a set of array.
//this is not hard corded, some times array will have multiple no.of strings in date format.
["vishnu","2016-08-31T18:30:00.000Z","1992","banglore"]
I have an array of strings, among these strings there is one string which is in date format.
I need to do a foreach and need to check which string is in the date format.
If we got the date string "2016-08-30T18:30:00.000Z" I need to convert it to basic date format but in correct timezone, here the date is 2016-08-31 but what I need as out put is
["vishnu","31/8/2016","1992","banglore"]
not
//check the difference in date!
["vishnu","30/8/2016","1992","banglore"]
the aim is from the array, if string is in date string format, convert it.
public static void Main(string[] args)
{
string inputString = "2016-08-31T18:30:00.000Z";
DateTime enteredDate = DateTime.Parse(inputString);
Console.WriteLine(enteredDate);
DateTime dDate;
if (DateTime.TryParse(inputString, out dDate))
{
DateTime dtx = enteredDate.ToLocalTime();
String.Format("{0:d/MM/yyyy}", dDate);
Console.WriteLine(dtx);
}
else
{
Console.WriteLine("Invalid"); // <-- Control flow goes here
}
// DateTime dt = convertedDate.ToLocalTime();
}
If you need to correct the DateTime for the time zone, you can use TimezoneInfo.ConvertTime():
string inputString = "2016-08-31T18:30:00.000Z";
DateTime dDate;
if (DateTime.TryParse(inputString, out dDate))
{
DateTime correctedDateTime = TimeZoneInfo.ConvertTime(dDate, TimeZoneInfo.Local);
// write this here back into the array using your format
Console.WriteLine(correctedDateTime.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture));
}
else
{
Console.WriteLine("Invalid"); // <-- Control flow goes here
}
For further reference check out this post. This answer is inspired by it to use TimeZoneInfo.
DateTime dDate;
do this operation iside foreach
if (DateTime.TryParse(answerString, out dDate))
{
DateTime enteredDate = DateTime.Parse(answerString);
var Date = enteredDate.ToString("dd/MM/yyyy");
answerString = Date;
Console.WriteLine(answerString);
}
else{
//operation
}
thanks to mong zhu
Try using DateTimeOffset rather than DateTime as it is built to handle time zones.
Here's the code:
string inputString = "2016-08-31T18:30:00.000Z";
DateTimeOffset enteredDate = DateTimeOffset.Parse(inputString);
Console.WriteLine(enteredDate);
DateTimeOffset dtx = enteredDate.ToLocalTime();
Console.WriteLine(dtx);
This produces the following for me in GMT+09:30:
2016/08/31 18:30:00 +00:00
2016/09/01 04:00:00 +09:30
To get it in Indian time try this:
DateTimeOffset dtx = enteredDate.ToOffset(TimeSpan.FromHours(5.5));
Console.WriteLine(dtx);
I get 2016/09/01 00:00:00 +05:30 now.

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

How to cast this date pattern?

I have a date with this pattern:
var value = "2013/11/07 23:08:53 +0000"
When I do:
var date = (DateTime)value;
I get an InvalidCastException. How can I cast that date?
You can't cast a string to a DateTime. Instead use DateTime.Parse(value) to parse the value.
You can also use DateTime.TryParse(string) to avoid throwing an exception.
var value = "2013/11/07 23:08:53 +0000";
DateTime dateTime;
if(DateTime.TryParse(value, out dateTime))
{
// The string is a valid DateTime
// This will output '11:08 PM'
Console.WriteLine(dateTime.ToShortTimeString());
}
else
{
// The string is not a valid DateTime
}

Get Date from DateTime without ToShortDateString

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");
}
}

Categories

Resources