C# string to SqlDateTime: how to set format for recognition? - c#

I need to use
SqlDateTime.Parse(val)
where val is a string such as " 23.3.1992 00:00:00 ".
The string is in European format, that is, day precedes month. However Parse wants "American" format. How I can tell it to use particular datetime format / locale?
Thanks in advance!

Try this:
string val = "23.12.1992 00:00:00";
// Parse exactly from your input string to the native date format.
DateTime dt = DateTime.ParseExact(val, "dd.M.yyyy hh:mm:ss", null);
// Part to SqlDateTime then
System.Data.SqlTypes.SqlDateTime dtSql = System.Data.SqlTypes.SqlDateTime.Parse(dt.ToString("yyyy/MM/dd"));
This could be done in one statement, but just separated for illustration.

Have you tried DateTime instead of SQLDateTime
DateTime d = DateTime.Parse(val);
String s = d.ToString(CultureInfo.CreateSpecificCulture("en-US"));

Can you try this ?
string valInEuropean = "23.3.1992 00:00:00";
DateTime dateInEuropean = DateTime.Parse(valInEuropean);
string valInAmerican = dateInEuropean.ToString("yyyy-MM-dd HH:mm:ww");

For converting a string to datetime object when the format is known(in this case )
use
DateTime dwweek = DateTime.ParseExact("23.3.1992 00:00:00", "dd.MM.yyyy hh:mm:ss", System.Globalization.CultureInfo.InvariantCulture);

Related

C#: Is this possible to convert 24hrs format string Datetime to 12hrs AM/PM dateformat (again in string only)

I have a date/time return from a C# method is in string,
string dateTime = "2018-6-18 20:50:35"
Now I would like to convert this into another string representation like,
string convertDT = "2018-6-18 08:50:35 PM"
Is this possible?
Seems like I can do something like,
var formattedTime = dateTime.ToString("h:mm tt", CultureInfo.InvariantCulture);
but not working. Suggestion please!
Just parse the string into a new DateTime object and then call ToString() with the right formats:
string dateTime = "2018-6-18 20:50:35";
DateTime parsedDateTime;
if(DateTime.TryParse(dateTime, out parsedDateTime))
{
return parsedDateTime.ToString("yyyy-M-d hh:mm tt");
}
The benefit of my answer is that it contains validation (DateTime.TryParse()), it results in a couple extra lines of code but you can now accept all input and not worry about an exception being thrown.
Even better would be to refactor this logic into its own method that you can re-use:
public static bool TryChangeDateTimeFormat(string inputDateString, string outputFormat, out string outputDateString)
{
DateTime parsedDateTime;
if(DateTime.TryParse(inputDateString, out parsedDateTime))
{
outputDateString = parsedDateTime.ToString(outputFormat);
return true;
}
outputDateString = string.Empty;
return false;
}
This returns a bool of whether or not the conversion was successful and the out variable will be modified depending on the result.
Fiddle here
Without adding any validation,
var string24h = "2018-6-18 20:50:35";
var dateTime = DateTime.Parse(string24h);
var formattedTime = dateTime.ToString("h:mm tt", CultureInfo.InvariantCulture);
Use DateTime.ParseExact and then ToString
Sure, you can use the DateTime class to parse the original string and then output a differently formatted string for the same date:
string result = DateTime.Parse(dateTime).ToString("h:mm tt", CultureInfo.InvariantCulture);
var dateTime = "2018-6-18 20:50:35";
var dt = Convert.ToDateTime(dateTime);
var amPmDateTime = dt.ToString(#"yyyy-MM-dd hh:mm:ss tt", CultureInfo.InvariantCulture);
To give you exactly your format you would use
string convertDT = DateTime.Parse(dateTime).ToString("yyyy-MM-dd hh:mm:ss tt");
You can change the format between the quotes however you would like. For example yyyy/MM/dd or something. Just remember MM is 2 spots for months and mm is 2 spots for minutes.
So if you put
string convertDT = DateTime.Parse(dateTime).ToString("yyyy-mm-dd hh:mm:ss tt");
You are going to get year - minutes - days.

Assign value of a string (containing date and time) to two different variable (one for Date and one for Time)

I have a string ("CompletionDate") which contains the value "2/28/2017 5:24:00 PM"
Now I have 2 variables (EDate and ETime). I want to assign the Date to EDate (i.e 2/28/2017) and Time to ETime (i.e. 5:24:00 PM).
How can I split the Date and Time from a single string.
Kindly Help.
My approach right now is like :
string CompletionDate = string.Empty;
string ProjectEDate = string.Empty;
string ProjectETime = string.Empty;
CompletionDate = "2017-03-29 12:58:00";
DateTime dt = DateTime.ParseExact(CompletionDate, "yyyy-MM-dd", CultureInfo.CreateSpecificCulture("en-us"));
DateTime dt1 = DateTime.ParseExact(CompletionDate, "HH:mm:ss", CultureInfo.CreateSpecificCulture("en-us"));
var ProjectEDate = dt.ToString();
var ProjectETime = dt1.ToString();
But its throwing exception that string is not in correct format. Kindly help
#Chris pointed one of your problems, but you have one more. You are passing full date time string and trying to treat it as date or time only, which is not true. Instead I suggest you to parse DateTime object with both date and time, and then take whatever you need from parsed object:
CultureInfo enUS = CultureInfo.CreateSpecificCulture("en-us");
DateTime dt = DateTime.ParseExact(CompletionDate, "yyyy-MM-dd HH:mm:ss", enUS);
var ProjectEDate = dt.Date.ToString();
var ProjectETime = dt.TimeOfDay.ToString();
You need to specify the full format as same as the input string to parse method.
DateTime dt = DateTime.ParseExact(CompletionDate, "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.CreateSpecificCulture("en-us"));
To get results you can use below methods available by default in DateTime.
dt.ToShortTimeString()
"12:58 PM"
dt.ToLongTimeString()
"12:58:00 PM"
dt.ToLongDateString()
"Wednesday, March 29, 2017"
dt.ToShortDateString()
"3/29/2017"
Or you can specify the format to ToString method.
dt.ToString("yyyy-MM-dd")
"2017-03-29"
dt.ToString("HH:mm:ss")
"12:58:00"
DateTime.ParseExact(CompletionDate, "yyy-MM-dd", ...
You are missing 4th 'y' in date format string:
"yyyy-MM-dd"
^
here
and:
String was not recognized as a valid DateTime " format dd/MM/yyyy"
Why do you parse into DateTime and then convert to a string using ToString again? CouldnĀ“t you just simply use String.Split when all you want is to split the time from the day and you know the exact format?
var CompletionDate = "2017-03-29 12:58:00";
var tmp = CompletionDate.Split(' ');
var ProjectEDate = tmp[0];
var ProjectETime = tmp[1];

Error when converting date to dd-MMM-yy

I am getting an error when I run the following line of code:
DateTime dt = DateTime.ParseExact(bolShipdate, "dd/MMM/yyyy", null);
The error is:
String was not recognized as a valid DateTime.
The bolShipdate value is 02-21-2016. I need to convert the date to 21-Feb-16.
How can I resolve this?
Your format in ParseExact needs to match your string. dd/MMM/yyyy doesn't match the sample data provided. try:
var bolShipdate = "02-21-2016";
DateTime dt = DateTime.ParseExact(bolShipdate, "MM-dd-yyyy", null);
Console.WriteLine(dt.ToString("dd-MMM-yy")); // Dispays 21-Feb-16
(Example fiddle)
Declaration of DateTime.ParseExact is
public static DateTime ParseExact(
string s,
string format,
IFormatProvider provider
)
Here you will want to pass the format you are parsing not the expected result. And it looks like your string is of the format MM-dd-yyyy.
You can then use .ToString(string format to get the date in your desired format:
string date = "02-21-2016";
DateTime dt = DateTime.ParseExact(date, "MM-dd-yyyy", CultureInfo.InvariantCulture);
string newFormat = dt.ToString("dd-MMM-yy");
Console.WriteLine(newFormat);
Hope this can resolve:
var date = "02-21-2016";
DateTime dt = DateTime.ParseExact(date, "MM-dd-yyyy", CultureInfo.InvariantCulture);
string result = dt.ToString("dd-MMM-yy");

How to convert any date format to yyyy-MM-dd

My app parses a string data, extracts the date and identify the format of the date and convert it to yyyy-MM-dd.
The source date could be anything lime dd-mm-yyyy, dd/mm/yyyy, mm-dd-yyyy, mm/dd/yyyy or even yyyy-MM-dd.
Other than attempting different permutations and combinations using switch case, is there any other efficient way to do it?
string sourceDate = "31-08-2012";
String.Format("{0:yyyy-MM-dd}", sourceDate);
The above code simply returns the same sourceDate "31-08-2012".
string DateString = "11/12/2009";
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime dateVal = DateTime.ParseExact(DateString, "yyyy-MM-dd", culture);
These Links might also Help you
DateTime.ToString() Patterns
String Format for DateTime [C#]
Convert your string to DateTime and then use DateTime.ToString("yyyy-MM-dd");
DateTime temp = DateTime.ParseExact(sourceDate, "dd-MM-yyyy", CultureInfo.InvariantCulture);
string str = temp.ToString("yyyy-MM-dd");
string sourceDateText = "31-08-2012";
DateTime sourceDate = DateTime.Parse(sourceDateText, "dd-MM-yyyy")
string formatted = sourceDate.ToString("yyyy-MM-dd");
You can write your possible date formats in array and parse date as following:
public static void Main(string[] args)
{
string dd = "12/31/2015"; //or 31/12/2015
DateTime startDate;
string[] formats = { "dd/MM/yyyy", "dd/M/yyyy", "d/M/yyyy", "d/MM/yyyy",
"dd/MM/yy", "dd/M/yy", "d/M/yy", "d/MM/yy", "MM/dd/yyyy"};
DateTime.TryParseExact(dd, formats,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out startDate);
Console.WriteLine(startDate.ToString("yyyy-MM-dd"));
}
You can change your Date Format From dd/MM/yyyy to yyyy-MM-dd in following way:
string date = DateTime.ParseExact(SourceDate, "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
Here, SourceDate is variable in which you will get selected date.
You will need to parse the input to a DateTime object and then convert it to any text format you want.
If you are not sure what format you will get, you can restrict the user to a fixed format by using validation or datetimePicker, or some other component.
This is your primary problem:
The source date could be anything like dd-mm-yyyy, dd/mm/yyyy,
mm-dd-yyyy, mm/dd/yyyy or even yyyy-MM-dd.
If you're given 01/02/2013, is it Jan 2 or Feb 1? You should solve this problem first and parsing the input will be much easier.
I suggest you take a step back and explore what you are trying to solve in more detail.
Try this code:
lblUDate.Text = DateTime.Parse(ds.Tables[0].Rows[0]["AppMstRealPaidTime"].ToString()).ToString("yyyy-MM-dd");
if (DateTime.TryParse(datetoparser, out dateValue))
{
string formatedDate = dateValue.ToString("yyyy-MM-dd");
}
string sourceDate = "15/06/2021T00.00.00";
DateTime Date = DateTime.Parse(sourceDate)
string date = Date.ToString("yyyy-MM-dd");
Convert.toDateTime(sourceDate).toString("yyyy-MM-dd");
Convert.ToDateTime((string)item["LeaveFromDate"]).ToString("dd/MM/yyyy")
This might be helpful

Parse C# string to DateTime

I have a string like this:
250920111414
I want to create a DateTime object from that string. As of now, I use substring and do it like this:
string date = 250920111414;
int year = Convert.ToInt32(date.Substring(4, 4));
int month = Convert.ToInt32(date.Substring(2, 2));
...
DateTime dt = new DateTime(year, month, day ...);
Is it possible to use string format, to do the same, without substring?
Absolutely. Guessing the format from your string, you can use ParseExact
string format = "ddMMyyyyHHmm";
DateTime dt = DateTime.ParseExact(value, format, CultureInfo.InvariantCulture);
or TryParseExact:
DateTime dt;
bool success = DateTime.TryParseExact(value, format,
CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
The latter call will simply return false on parse failure, instead of throwing an exception - if you may have bad data which shouldn't cause the overall task to fail (e.g. it's user input, and you just want to prompt them) then this is a better call to use.
EDIT: For more details about the format string details, see "Custom Date and Time Format Strings" in MSDN.
You could use:
DateTime dt = DateTime.ParseExact(
date,
"ddMMyyyyHHmm",
CultureInfo.InvariantCulture);
string iDate = "05/05/2005";
DateTime oDate = Convert.ToDateTime(iDate);
DateTime oDate = DateTime.ParseExact(iString, "yyyy-MM-dd HH:mm tt",null);
DateTime Formats

Categories

Resources