formatting Datetime string - c#

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/

Related

How to convert this UTC datetime string to DateTime object c#

I have been trying to convert this string to a DateTime object in C#
2019-09-23T08:34:00UTC+1
I've tried using DateTime.Parse but it is throwing an exception for
"String was not recognized as a valid DateTime."
I'm sorry but you seem like a victim of garbage in, garbage out.
That's an unusual format, that's why before I suggest a solution for you, first thing I want to say is "Fix your input first if you can".
Let's say you can't fix your input, then you need to consider a few things;
First of all, if your string has some parts like UTC and/or GMT, there is no custom date and time format specifier to parse them. That's why you need to escape them as a string literal. See this question for more details.
Second, your +1 part looks like a UTC Offset value. The "z" custom format specifier is what you need for parse it but be careful, this format specifier is not recommended for use with DateTime values since it doesn't reflect the value of an instance's Kind property.
As a solution for DateTime, you can parse it like I would suggest;
var s = "2019-09-23T08:34:00UTC+1";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy-MM-dd'T'HH:mm:ss'UTC'z", CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal, out dt))
{
Console.WriteLine(dt);
}
which gives you 2019-09-23 07:34:00 as a DateTime and which has Utc as a Kind property.
As a solution for DateTimeOffset - since your string has a UTC Offset value you should consider to parse with this rather than Datetime
-, as Matt commented, you can use it's .DateTime property to get it's data like;
var s = "2019-09-23T08:34:00UTC+1";
DateTimeOffset dto;
if(DateTimeOffset.TryParseExact(s, "yyyy-MM-dd'T'HH:mm:ss'UTC'z", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dto))
{
Console.WriteLine(dto.DateTime);
}
which gives you the same result DateTime but Unspecified as a .Kind property.
But, again, I strongly suggest you to fix your input first.
Use TryParseExact to convert the string to datetime. Here is the sample code to covert the given format(s) to datetime
private static DateTime ParseDate(string providedDate) {
DateTime validDate;
string[] formats = {
"yyyy-MM-ddTHH:mm:ss"
};
var dateFormatIsValid = DateTime.TryParseExact(
providedDate, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out validDate);
return dateFormatIsValid ? validDate: DateTime.MinValue;
}
Then, use this function to convert the string. I am replacing UTC+1 to empty string
static void Main(string[] args) {
string strdatetime = "2019-09-23T08:34:00UTC+1";
DateTime dateTime = ParseDate(strdatetime.Replace("UTC+1", ""));
Console.WriteLine(dateTime);
}

String Date To convert DateTime using ParseExact

I have a string and it comes as a DD/MM/YYYY style.(eg : 11/07/2018)
I need to convert this To DateTime format and YYYY-MM-DD style.
I tried it using DateTime.Parse but can't
if (!String.IsNullOrEmpty(fromDate))
{
frm = DateTime.ParseExact(fromDate, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None);
}
else if(!String.IsNullOrEmpty(toDate))
{
todt = DateTime.ParseExact(toDate, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None);
}
You can do this in one line of code.
var newDateString = DateTime.ParseExact(myDateString, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None).ToString("yyyy-MM-dd");
Keep in mind that a DateTime instance is a data structure that does not have a format. When dealing with dates and times it is best to only revert to a human readable string when you need to present/output the value for a human to read. For anything else including persistence to a storage system that supports types (like a relational database) leave the value as a DateTime type.
Example: If you wanted yyyy-MM-dd because you wanted to persist this to Sql Server then you should stop after the parsing (and not call ToString). You can then assign the DateTime instance to a command parameter's Value property directly.
Convert using ParseExact and then use ToString to the target format:
string dateS = "30/04/2018";
DateTime dateD = DateTime.ParseExact(dateS, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
string dateS2 = dateD.ToString("yyyy-MM-dd");
Here is a working example in fiddle: https://dotnetfiddle.net/e0yuZ6

how to input DateTime into MySQL via C#

I'm having a huge issue with inputting DateTime into my MySQL db. MySQL reads datetime as yyyy-MM-dd HH:mm:ss while C# sees datetime as dd/MM/yyyy HH:mm:ss. I have tried two different examples and both doesn't work.
MODEL
public class DateAndTime
{
public DateTime DateTime { get; set; }
}
CONTROLLER
//I Have two examples that doesn't work.
var myDateTime = "2016-04-08 12:00:00" //this gives the error "cannot covert source 'string' to tartget type System.DateTime
var myDateTime = Convert.ToDateTime("2016-04-08 12:00:00") //this gives the error "Input string was not in a correct format."
var model = new DateAndTime
{
DateTime = myDateTime
};
So I'm stuck. I'ms sure someone out there has had this issue.
DateTime myDate = DateTime.ParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff",
System.Globalization.CultureInfo.InvariantCulture);
Check:
Converting a String to DateTime
https://msdn.microsoft.com/en-ca/library/cc165448.aspx
https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
I have this issue because of the datetime format in my machine. If your desktop is configured like dd/mm/yy(the / symbol instead of -) then you have to replace - with / before converting. Please let me know
try this :
myDateTime.ToString("yyyy-MM-dd HH:mm:ss");
myDateTime variable must be type DateTime.
or you can use this MySql function : STR_TO_DATE
STR_TO_DATE('4/8/2016 2:18:17 PM', '%m/%d/%Y %h:%i:%s %p')
Specifier Format here

How to convert dd/mm to Mysql Datetime format in c#

I have a date string with dd/mm format like 06/03.Now i have to store this string into mysql table column with DATETIME format.
I am getting the problem as How can i add the current year generically because i don't want to hard code it.Subsequently how will i convert it into MySql DATETIME format for saving it.
Please help me .
You can use Parse method of DateTime:
DateTime dateTime = DateTime.Parse("06/03");
UPDATE
For your comment:
Also after parsing into DateTime i am getting date correct but time i
dont want to be 12:00:00 AM instead i want it to be 00:00:00.
12:00:00 AM corresponds to 00:00:00 only. You can verify that by getting Hour property which will return 0 and also TimeOfDay will too return 00:00:00.
Even if you try to parse exact date, it also creates the same format.
DateTime dateTime = DateTime.ParseExact("06/03 00:00:00", "dd/MM hh:mm:ss",
CultureInfo.InvariantCulture);
And you don't need conversion from DateTime object to SQL compliant DateTime object. You can pass the .Net object to SQL writer.
Consider the code:
C#
string s = "06/03";
System.DateTime dateNow = Convert.ToDateTime(s);
will give the output as you required
in VB.Net :
Dim s As String = "06/03"
Dim dateNow As Date = CDate(s)
MsgBox(dateNow)
You could do something like
var some_date = "06/03";
var year = DateTime.Now.Year;
var option = some_date+"/"+year;
Or use any of the string formats to bend it to your needs
More on date string format can be found on this MSDN page.
Edit:
If you want zeroes in the time, like your comment said, you can usit Rohit vats answer and do:
DateTime dateTime = DateTime.Parse("06/03");
var s1 = dateTime.ToString("MM/dd/yy 00:00:00");
// Output: 03/06/14 00:00:00
var s2 = dateTime.ToString("MM/dd/yyyy 00:00:00");
// Output: 03/06/2014 00:00:00

How to change custom string format to Datetime format in Asp.net mvc

I have textbox asssociated with model class having value like
"03/28/2014".
I want to convert this to DateTime with 28/03/2014 format. I have tried following ways, but I'm not getting anywhere close...
IFormatProvider theCultureInfo = new System.Globalization.CultureInfo("en-US", true);
string date = timesheetModel.START_DATE;
string pattern = "dd-mm-yyyy";
DateTime dt=DateTime.ParseExact(date,pattern,theCultureInfo).
DateTime dt= Convert.ToDateTime(timesheetModel.START_DATE);
and also DateTime.Parse(date);
By this getting compile time error:
"String was not recognized as a valid DateTime."
I have tried also in modal class with Types like:
public string date{get;set;} // by this type not converting to datetime
public DateTime date{get;set;} // not able to access values to controller
Is there any other solution for this? Because the textbox value format is fixed.
I guess you should Use DateTime.ParseExact with the format "dd/MM/yyyy"
var result = DateTime.ParseExact("03/28/2014", "MM/dd/yyyy", CultureInfo.InvariantCulture)
.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
you can go though the below link for more information
http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx

Categories

Resources