String was not recognized as a valid DateTime - c#

I want to add a date in session (date1) like this:
Session["DateLesson"] = date1.ToString("dd.MM.yyyy");
Now from the session I want take this value:
var asd = Session["DateLesson"];
/*asd = "20.04.2012"*/
var datelesson = DateTime.Parse((string) asd);
And it gives me this exception:
FormatException not recognized as a valid DateTime

A period is not a valid/standard separator character in most locales. You'll need to use DateTime.ParseExact() in combination with a format string to tell the function how to read it. More importantly, if reading it back to a datetime is your main goal, why not just put the datetime in the session as is? That seems way more efficient, easier, and more maintainable to me.

Why persist your date as a string?
You could simply store it like this:
Session["DateLesson"] = date1;
And then retrieve it like this:
var datelesson = (DateTime)Session["DateLesson"];

string value = "20.04.2012";
DateTime datetime = DateTime.ParseExact(value, "dd.MM.yyyy", null);
This will return 4/20/2012 12:00:00:00 AM

Don't keep value as a string but as an object of the initial type:
public DateTime? DateLesson
{
get
{
DateTime? dateTime = Session["DateLesson"] as DateTime?;
if (dateTime.HasValue) // not null
{
// use dateTime.Value
}
}
set
{
Session["DateLesson"] = value;
}
}

Related

C# DateTime and String value condition check

I have a problem.
This is not working
> var from = "";
> StartDTime = Convert.ToDateTime(from);
This is working
> var from = "2021-10-05";
> StartDTime = Convert.ToDateTime(from);
Some time I'm sending Date Value, but sometime in not sending Date Value.in that time from variable pass as a empty string. I want to set if from variable is = "" then need to set default Date Value.so how can I resolve this?. Please help me guys. Thank you
A safe way of doing that would be:
StartDTime = string.IsNullOrEmpty(from) ? DateTime.Now : DateTime.Parse(from);
But if you have control over the code passing the "from" variable, you can declare it as nullable DateTime, then your code would look like this:
DateTime? from = null;
var StartDTime = from.HasValue ? from.Value : DateTime.Now;
Which for short would be:
StartDTime = from ?? DateTime.Now;
DateTime.TryParse will do the job for you:
for example:
DateTime dateTime;
var from = "";
DateTime.TryParse(from, out dateTime);
One-liner, with only the validation you specify:
StartDTime = from == "" ? new DateTime() : Convert.ToDateTime(from);
It's not ellegant, but works.
var from = "";
if(from == ""){ from = DateTime.MinValue.ToString(); }
DateTime StartDTime = Convert.ToDateTime(from);
But i think that a nullable DateTime would be more elegant, like this:
var from = null;
DateTime? StartDTime = from;
Or you can set a default date, like this:
var from = null;
DateTime? StartDTime = from ?? YourDefaultDate;
Convert methods either successfully convert the string passed to it, or throws an error, that's the way it's supposed to work. For most data types there are also TryParse methods that return true/false based on if it converted successfully and have an output variable which will be DateTime.MinValue if it failed. This is how I would handle your situation:
DateTime startDTime;
string from = "";
if (!DateTime.TryParse(from, out startDTime)){
startDTime = DateTime.Now;
}
This will set the startTime to the date passed in from, but if no date was passed it sets it to the current date and time - if you want a different default value, that replaces new DateTime() and if your default should be January 1, 0001, then you can just use the TryParse part directly, since that's the automatic default for a failed TryParse.

Cannot convert date into specific format

I'm trying to convert a Date into a specific format, I saw a lot of questions here with the same target but all the proposed solutions return a string, I need to return a DateTime in my custom format.
This is my code:
private DateTime? _matchCalendarDate = DateTime.Now;
public DateTime? MatchCalendarDate
{
get
{
var date = _matchCalendarDate.Value.ToString("dd-MM-yyyy");
var c = DateTime.ParseExact(date, "dd-MM-yyyy", CultureInfo.InvariantCulture);
return c;
}
set
{
_matchCalendarDate = value;
OnPropertyChanged();
}
}
this return: 8/15/2018 12:00:00 AM but should return 15/08/2018
When you say it returns 8/15/2018 12:00:00 AM, I'm guessing you're simply calling ToString() on the property, like so:
MatchCalendarDate.ToString();
The thing is, a DateTime object doesn't have it's own inherent 'format'. It's format is whatever you want it to be.
So when you actually use the property to print the value it returns, you can choose how you want it do be displayed.
Something like;
MatchCalendarDate.ToString("dd-MM-yyyy");
But then, that essentially renders the conversion in your property redundant. So assuming your intention is to store a DateTime object, but retrieve it in the format you like, what you should do is declare a second string property that does the conversion for you.
Return matchCalendarDate.Date; returns the date component, time set to zero
You may have to consider converting to the original format first then to your required format
private DateTimeDateTime _matchCalendarDate, _matchCalendarD = DateTime.Now;
public DateTime MatchCalendarDate
{
get
{
var date = _matchCalendarDate.Value.ToString("dd-MM-yyyy");
var dt = DateTime.ParseExact(date, "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
var c = dt.ToString("dd/M/yyyy", CultureInfo.InvariantCulture);
return c;
}
set
{
_matchCalendarDate = value;
OnPropertyChanged();
}
}

Remove time from time and date

I have a variable openDate which holds date and time, and I would like to strip just the date. I tried the below example and it is not working. What am I doing wrong, or rather how should I do it because the variable openDate remains the same even after trying to strip just the date? The value of openDate is "2012-03-08 00:00:00"
openDate = ! string.IsNullOrEmpty(node.ChildNodes[f].Attributes["ows_PMO_x0020_Origination_x0020_Date"].Value)
? node.ChildNodes[f].Attributes["ows_PMO_x0020_Origination_x0020_Date"].Value
: "" ;
openDate = String.Format("{0:MM/dd/yyyy}", openDate);
considering openDate is of a String type, i would do this
var dt = DateTime.Parse(openDate).ToString("MM/dd/yyyy");
From your code it is clear that openDate is of type string and you have value that is a string representation of DateTime, you can apply DateTime formatting on string values.
You have multiple options.
Convert string openDate to a DateTime value and then apply formatting
Do some string operations to extract the date part from your string value.
String operations:
string openDate = "2012-03-08 00:00:00";
string formatted = openDate.Substring(0, openDate.IndexOf(' '));
DateTime Parsing.
DateTime parsedDateTime = DateTime.Parse(openDate);
string formattedDateTime = parsedDateTime.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);
You need to convert your date into a DateTime object first. See examples here if your string is in a different or custom format.
openDate = !string.IsNullOrEmpty(node.ChildNodes[f].Attributes["ows_PMO_x0020_Origination_x0020_Date"].Value)? node.ChildNodes[f].Attributes["ows_PMO_x0020_Origination_x0020_Date"].Value: "" ;
//openDate is a string at this point. You'll need to convert it to a datetime object first, for the following line to work:
var dtObject = DateTime.Parse(openDate);
//Format the newly created datetime object
openDate = String.Format("{0:MM/dd/yyyy}", dtObject);
You can format datetime using:
If it is a datetime:
OpenDate = OpenDate.ToString("yyyy-mm-dd");
If the datatype is not datetime and you are sure the format will always be that then you can always convcert the string to datetime and use the method described above.
Convert.ToDateTime(openDate).ToString("yyyy-mm-dd");
The answers are great, especially if you would like to control the format of your 'time' part. Here is teh simplest way to get what you are after:
var dt = Convert.ToDateTime("2012-03-08 00:00:04");
Console.WriteLine(dt.ToLongTimeString());
Console.WriteLine(dt.TimeOfDay);
Output:
Use the following - openDate = openDate.Date

Hour from DateTime? in 24 hours format

So i have this DateTime? and what i want to do is to obtain the hour but show it in 24 hours format.
For example:
If the hour is 2:20:23 p.m. i want to convert it to 14:20 and that's it.
I'm working with Visual C#.
Any ideas please, thank you.
I have something like this
public static string FormatearHoraA24(DateTime? fechaHora)
{
if (!fechaHora.HasValue)
return "";
string retornar = "";
//here goes what i need
}
You can get the desired result with the code below. Two 'H' in HH is for 24-hour format.
return fechaHora.Value.ToString("HH:mm");
date.ToString("HH:mm:ss"); // for 24hr format
date.ToString("hh:mm:ss"); // for 12hr format, it shows AM/PM
Refer this link for other Formatters in DateTime.
Using ToString("HH:mm") certainly gives you what you want as a string.
If you want the current hour/minute as numbers, string manipulation isn't necessary; you can use the TimeOfDay property:
TimeSpan timeOfDay = fechaHora.TimeOfDay;
int hour = timeOfDay.Hours;
int minute = timeOfDay.Minutes;
Try this:
//String.Format("{0:HH:mm}", dt); // where dt is a DateTime variable
public static string FormatearHoraA24(DateTime? fechaHora)
{
if (!fechaHora.HasValue)
return "";
return retornar = String.Format("{0:HH:mm}", (DateTime)fechaHora);
}
Try this, if your input is string
For example
string input= "13:01";
string[] arry = input.Split(':');
string timeinput = arry[0] + arry[1];
private string Convert24To12HourInEnglish(string timeinput)
{
DateTime startTime = new DateTime(2018, 1, 1, int.Parse(timeinput.Substring(0, 2)),
int.Parse(timeinput.Substring(2, 2)), 0);
return startTime.ToString("hh:mm tt");
}
out put: 01:01
Another method
var time = DateTime.Now;
string foo = $"{time:HH:mm}";
Where I find this useful is if there is more than just the time in the string.
string bar = $"The time is {time:HH:mm}";

How to compare a DateTime to a string

I have string which contains a time (obtained from a DB):
string user_time = "17:10:03"; //Hours:minutes:seconds
DateTime time_now = DateTime.Now;
How do I compare this string to a DateTime? I'd like something like this:
if(time_now > user_time)
{
//Do something
}
else
{
//Do something
}
DateTime supports comparison, but first you need to parse the date-time string, DateTime.Parse() should suffice:
var dateTimeStr = "17:10:03";
var user_time = DateTime.Parse( dateTimeStr );
var time_now = DateTime.Now;
if( time_now > user_time )
{
// your code...
}
Bear in mind, that comparing dates/times sometimes requires awareness of time-zones to make the comparison meaningful.
The problem is that DateTime.Now includes a date, "17:10:03" doesn't. Do it like this:
Dim dbaseTime As TimeSpan = TimeSpan.Parse("17:10:03")
If DateTime.Now.TimeOfDay > dbaseTime Then
Console.WriteLine("Let's go home")
End If
Do everything in your power to convert that string column type to a datetime column.
You can use DateTime.Compare() along with DateTime.Parse() to convert the string to a DateTime object.
DateTime.Parse Will convert the string into a DateTime object which you can then use to compare.
if (DateTime.Now > DateTime.Parse(user_time))
{
...
}
But you really shouldn't store a time as a string, you should use the native time or datetime format of your database, that way you could use the value of the time in your queries, and index them properly.
if (time_now > Date.Parse(DBString)) {
} else {
}

Categories