Convert date from Spanish to English - c#

Current culture of my application is set to Spanish but i need to convert my date to English in order to perform database operations.
currently date is coming in this format: "Dic 13, 2017"
I need to convert this to : "Dec 13, 2017"
what i have tried until now
var input = objDMSampleA.RequestDateFrom;
var format = "MMM dd, yyyy";
var dt = DateTime.ParseExact(input, format, new CultureInfo("es-ES"));
var result = dt.ToString(format, new CultureInfo("en-US"));
but the ParseExact gives error that
String was not recognized as a valid DateTime.

"Short" month names for given culture are stored in CultureInfo.DateTimeFormat.AbbreviatedMonthNames. For es-ES culture those names might have dot in the end (for example: "dic." instead of "dic"). For that reason, parsing your string fails - "Dic" doesn't have that dot.
To fix this, one way is to modify those names:
var esCulture = new CultureInfo("es-ES");
var monthNames = esCulture.DateTimeFormat.AbbreviatedMonthNames;
for (int i = 0; i < monthNames.Length; i++) {
monthNames[i] = monthNames[i].TrimEnd('.');
}
esCulture.DateTimeFormat.AbbreviatedMonthNames = monthNames;
monthNames = esCulture.DateTimeFormat.AbbreviatedMonthGenitiveNames;
for (int i = 0; i < monthNames.Length; i++)
{
monthNames[i] = monthNames[i].TrimEnd('.');
}
esCulture.DateTimeFormat.AbbreviatedMonthGenitiveNames = monthNames;
Then your code will work as expected:
var input = "Dic 13, 2017";
var format = "MMM dd, yyyy";
var dt = DateTime.ParseExact(input, format, esCulture);
var result = dt.ToString(format, new CultureInfo("en-US"));
It's better to store modified culture in some static field and reuse it, instead of creating it and changing every time.
If you want to modify current culture for all threads, use
CultureInfo.DefaultThreadCurrentCulture = esCulture;
though I won't recommend doing that.

Related

How to convert string into date time with milliseconds in C#

How do I convert this string into a date time with milliseconds
03/04/2019 15:16:57.73
The format is day/month/year hour:minutes:seconds.milliseconds.
I tried it like this:
var format = "dd/MM/yyyy HH:mm:ss.fff";
var year = dateTime.Substring(0, 4);
var month = dateTime.Substring(4, 2);
var day = dateTime.Substring(6,2);
var hour = dateTime.Substring(8, 2);
var minute = dateTime.Substring(10, 2);
var seconds = dateTime.Substring(12, 2);
var miiliseconds = dateTime.Substring(14, 2);
var stringDate = $#"{day}/{month}/{year} {hour}:{minute}:{seconds}.{miiliseconds}";
var transactioDateTime = DateTime.ParseExact(stringDate, format, CultureInfo.InvariantCulture);
But I get an error of
Additional information: String was not recognized as a valid DateTime.
Can you please help me with this? Thank you.
Seems like you don't need substrings at all.
Just put your date string right into ParseExact and you will get what you want.
However the error there is because you have different milliseconds format: it expects you will put three digits there but you passed only two:
var dateTime = "03/04/2019 15:16:57.73";
var format = "dd/MM/yyyy HH:mm:ss.ff"; - this is the fix.

Parse date with any separator

I have an object that stores info about its content.
var columnType = new ColumnType
{
ColumnName = "DateTime D/M/Y",
ColType = typeof (DateTime),
Format = "ddMMyyyy HH:mm"
}
Based on that I need to parse rows before adding them to this column. The problem is that my format doesn't include separators. I want to parse the date no matter what separator.
The standard DateTime.Parse doesn't have a constructor with format, and DateTime.ParseExact expects that the specified format already has separators in it.
I need something that will parse date like that:
If my format is ddMMyyyy HH:mm, then:
05.03.2016 04:19 -> parsed
05-03-2016 04:19 -> parsed
05/03/2016 -> parsed (time should be optional)
2016/03/05 04:19 -> error
I tried to do this, but without separators in format it didn't work:
var format = "ddMMyyyy HH:mm";
DateTime.TryParseExact("05.03.2016 04:19", format, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime resultValue);
DateTime.Parse works with the samples depending on the IFormatProvider:
var ci = new CultureInfo("pl");
var d1 = DateTime.Parse("05.03.2016 04:19", ci);
var d2 = DateTime.Parse("05-03-2016 04:19", ci);
var d3 = DateTime.Parse("05/03/2016" , ci);
var d4 = DateTime.Parse("2016/03/05 04:19", ci);
Something like this may work for you. This first snippet doesn't deal with optional time, see below.
char[] separators = { '/', '-', '.', '#', '#' };
string format = "dd?MM?yyyy HH:mm"; // ? replaced with each separator
// Create and populate an array of all acceptable formats
string[] formats = new string[separators.Length];
for (int i = 0; i < separators.Length; i++)
{
formats[i] = format.Replace('?', separators[i]);
}
DateTime dt;
if (DateTime.TryParseExact("05#12#2017 15:36", formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
// Use dt
}
else
{
// No format matched
}
This works by using DateTime.TryParseExact that accepts a string array of formats, rather than one single format. This works because:
The format of the string representation must match at least one of the specified formats exactly.
It must be noted that all the separators must be the same in the input string, no mix and match.
For optional time you could add other formats that do not include HH:mm. For example:
...
string formatWithTime = "dd?MM?yyyy HH:mm";
string formatWithoutTime = "dd?MM?yyyy";
List<string> f = new List<string>();
foreach (char c in separators)
{
f.Add(formatWithTime.Replace('?', c));
f.Add(formatWithoutTime.Replace('?', c));
}
string[] formats = f.ToArray();
...

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];

To Get Date From DateTime Variable

I have a variable testDate which contains value {01/02/2016 AM 12:00:00}. I need to get only date part from the set. For that I used below code:
var testDate = startDate.AddDays(i);
var testDateOnly = testDate.Date;
But it returns the same {01/02/2016 AM 12:00:00}.
The date variable will contain the date, the time part will be 00:00:00
http://msdn.microsoft.com/en-us/library/system.datetime.date.aspx
// The date with time component
var testDate = startDate.AddDays(i);
// Get date-only portion of date, without its time (ie, time 00:00:00).
var testDateOnly = testDate.Date;
// Display date using short date string.
Console.WriteLine(testDateOnly.ToString("d"));
// OUTPUT will be 1/2/2016
var testDate = startDate.AddDays(i);
string dateOnlyString = testDate.ToString("dd-MM-yyy");
"dd-MM-yyy" this will be the Date Format of the output string, You can choose the format as per your requirements.
You can use the following also for formatting:
dateOnlyString = d.ToString("M/d/yyyy"); // "3/9/2008"
dateOnlyString = d.ToString("MM/dd/yyyy}"); // "03/09/2008"
// day/month names
dateOnlyString = d.ToString("ddd, MMM d, yyyy}"); // "Sun, Mar 9, 2008"
dateOnlyString = d.ToString("dddd, MMMM d, yyyy}"); // "Sunday, March 9,2008"
// two/four digit year
dateOnlyString = d.ToString("MM/dd/yy}"); // "03/09/08"
dateOnlyString = d.ToString("MM/dd/yyyy}"); // "03/09/2008"
You need to convert the Date in to String type using this,
var testDate = startDate.AddDays(i);
var testDateOnly = testDate.Date.ToShortDateString(); //string
or
var testDateOnly = testDate.Date.ToString("dd/MM/yyyy");
or
var testDateOnly = testDate.Date.ToString("d");
Check it here.
Find the more about Standard Date and Time Format Strings
You will get the dd-MM-yyyy format by doing this.

Excel decimal format to C# DateTime

In my C# Data Access Layer...I am retrieving a dataset from Excel ...and there is a decimal excel field which returns date in the format : 20090701. I need this to be converted to C# DateTime. What is the best way to do it?
DateTime.ParseExact( value.ToString(), "yyyymmdd" );
The ParseExact method allows you to specify the format string for the date/time you are converting. In your case: a four digit year, then two digit month, then two digit day of month.
I would do something like this if you want to implement it application wide.
System.Globalization.CultureInfo cultureInfo =
new System.Globalization.CultureInfo("en-CA");
// Defining various date and time formats.
dateTimeInfo.LongDatePattern = "yyyyMMdd";
dateTimeInfo.ShortDatePattern = "yyyyMMdd";
dateTimeInfo.FullDateTimePattern = "yyyyMMdd";
// Setting application wide date time format.
cultureInfo.DateTimeFormat = dateTimeInfo;
// Assigning our custom Culture to the application.
//Application.CurrentCulture = cultureInfo;
Thread.CurrentThread.CurrentCulture = cultureInfo;
Thread.CurrentThread.CurrentUICulture = cultureInfo;
DateTime.Parse(excelDate);
And a less intuitive answer for good measure.
var a = 20090701m;
var b = a / 10000;
var year = (int)b;
var c = (b - year) * 100;
var month = (int)c;
var day = (int)((c - month) * 100);
var dt = new DateTime(year, month, day);

Categories

Resources