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
}
Related
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;
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.
I have create one helper method that convert UTC date time to specific time zone datetime.
public DateTime ConvertToSpecificTimeZone(DateTime utcDateTime, string utcOffset)
{
return ConvertTimeZone(utcDateTime, utcOffset.Trim());
}
private DateTime ConvertTimeZone(DateTime dateTime, string timeOffset)
{
int offsetSign = (timeOffset.StartsWith("-") ? -1 : 1);
timeOffset = timeOffset.TrimStart('+').TrimStart('-');
if (timeOffset == "00:00")
{
return dateTime;
}
else
{
string[] offsetArgs = timeOffset.Split(':');
return dateTime.AddHours(Int32.Parse(offsetArgs[0]) * offsetSign).AddMinutes(Int32.Parse(offsetArgs[1]) * offsetSign);
}
}
And when calling it from ItemController in MVC project
StartDate = new Helper().ConvertToSpecificTimeZone(properties.StartDate, this.UTCTimeOffset).ToString("MM/dd/yyyy");
and it sometime give error like
System.ArgumentOutOfRangeException: The added or subtracted value
results in an un-representable DateTime. Parameter name: value at
System.DateTime.AddTicks(Int64 value) at
Myproject.Utility.Helper.ConvertTimeZone(DateTime dateTime, String
timeOffset) at Myproject.Controllers.ItemController.Manage(String
param)
Please tell me how to handle this error in my code.
My guess is that you have an unitialized datetime in properties.StartDate variable.
Unitialized datetimes hold the value of 1/1/0001 12:00:00.
You can add this check on your ConvertTimeZone function to catch this kind of issues or/and try to fix your business logic flow.
if (dateTime == default(DateTime))
throw new ArgumentOutOfRangeException("Please set the initial datetime value");
I have passing a date in query string as the format of 02-2014.and using this date I done the search.It is working and the result is perfect .but when I change the query string value in the browser then the error will showing.In this condition I need only some message,So how can we check the query string date value is in correct format.my code is
string dateToSearch = HttpContext.Current.Request["date"];
if (!string.IsNullOrEmpty(dateToSearch))
{
dateToSearch = dateToSearch.Trim();
string year = null;
string month = null;
var dates = dateToSearch.Split("-".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
if (dates.Length > 0)
{
month = dates[0];
year = dates[1];
}
}
Just use DateTime.TryParseExact with the format string MM-yyyy. This will tell you whether your input string is in the format you specified and if so, it returns the parsed DateTime object via an out parameter.
Try this:
DateTime date;
if (DateTime.TryParseExact(text, "MM'-'yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out date))
{
// Success
}
else
{
// Parse failed
}
I am trying to format date in a specific order
Time = DateTime.Parse(p.Time.ToString("dd-MM-yyyy HH:mm:ss"))
Data type of Time is DateTime
But i am getting this error:
No overload for method "ToString" takes 1 arguments.
p is the object of the table from which i am getting Time.
List<ProductImageMapWrapper> lstpm = new List<ProductImageMapWrapper>();
lstpm = _db.ProductImageMaps.Where(i => i.ClientId == null && i.BrandId == null).Select(p => new ProductImageMapWrapper
{
Time= // Problem here
}
Now, I tried using it this way
Time = DateTime.Parse(string.Format("{dd-MM-yyyy HH:mm:ss}", p.Time))
but then i got this error:
LINQ to Entities does not recognize the method System.DateTime Parse(System.String) method, and this method cannot be translated into a store expression.
String Time = Convert.ToDateTime(p.Time).ToString("dd-MM-yyyy HH:mm:ss");
It looks to me like the Time property of both types (ProductImageMap and ProductImageMapWrapper) is a DateTime. If that is true, then you should use Time = p.Time
There's a common misconception that a DateTime value somehow has a format. Actually, you apply a given format when you convert the DateTime value into a string. To copy a DateTime value from one place to another, just assign it.
parenthesis are in the wrong place. You cannot parse it as that format. You have to parse P, then format as the string.
DateTime.Parse(System.DateTime.Now).ToString("dd-MM-yyyy HH:mm:ss")
Here is the example how to parse date from string and you can correct this for your structure to work:
string p = "21-11-2013 11:12:13";
DateTime time = DateTime.ParseExact(p, "dd-MM-yyyy HH:mm:ss", System.Globalization.CultureInfo.CurrentCulture);
Considering p.Time as string value in the date format you suggested, I think you want to parse string to DateTime as,
CultureInfo provider = CultureInfo.InvariantCulture;
string format = "dd-MM-yyyy HH:mm:ss"; //This should be format that you get in string
List<ProductImageMapWrapper> lstpm = new List<ProductImageMapWrapper>();
lstpm = _db.ProductImageMaps.Where(i => i.ClientId == null && i.BrandId == null).Select(p => new ProductImageMapWrapper
{
Time = DateTime.ParseExact(p.Time, format, provider)
});
Might Help
var selectQuery=from add in db.address
select add.myDate.toString("{0:dddd, MMMM d, yyyy}");
selectQuery.Distinct();
Normal Convers.
DateTime time = DateTime.Now; // Use current time
string format = "MMM ddd d HH:mm yyyy"; // Use this format
Console.WriteLine(time.ToString(format));
1.MMM display three-letter month
2.ddd display three-letter day of the WEEK
3.d display day of the MONTH
4.HH display two-digit hours on 24-hour scale
5.mm display two-digit minutes
6.yyyy displayfour-digit year
You want to use DateTime.ToString(format) not Nullable.ToString(no
overload):
DateTime? myDate = form.dteStartDate;
string sqlFormattedDate = myDate.Value.ToString("yyyy-MM-dd HH:mm:ss");
Of course this doesn't handle the case that there is no value. Perhaps something like this:
string sqlFormattedDate = myDate.HasValue
? myDate.Value.ToString("yyyy-MM-dd HH:mm:ss")
: "<not available>";