I am working WPF application using C# and .Net Framework 4.0. I want to change the format of the date and display in my application screen. Currently I am displaying the date in this format - mm/dd/yyyy that is (01/27/2017). I want to change the format from "01/27/2017" to "26JA2017".
I tried the below code,
value = Convert.ToDateTime(currentDate).ToString("ddMMMyyyy");
The above code is changing the date from "01/27/2017" to "27JAN2017". I want it to be 27JA2017. The customer is from France and he need the date format to be in French.
Can anyone of you help me in converting the date format from "27JAN2017" to "27JA2017"?
First of all, if you need a date in a language-specific format, you should pass the appropriate CultureInfo to ToString:
.ToString(..., CultureInfo.GetCultureInfo("fr-FR"));
Furthermore, this is ambiguous and not a standard format, so the easiest way is to just use a lookup table for the months and construct the string yourself.
As far as I can guess, you want kind of Canadian abbreviation:
http://interglacial.com/pub/text/Canadian_month_abbreviations.html
which is English/French names compromise
The reason that the abbreviations are a little odd at points is that
they're based on a compromise between the full English month names and
the full French month names
If it's your case, I suggest using custom DateTime Format:
// fr-FR - France (The customer is from [Mainland?] France)
// fr-CA - Canada (Origin of the abbreviations)
DateTimeFormatInfo caFormat =
(DateTimeFormatInfo) (CultureInfo.GetCultureInfo("fr-FR").DateTimeFormat.Clone());
caFormat.AbbreviatedMonthNames = new string[] {
"JA", "FE", "MR", "AL", "MA", "JN", "JL", "AU", "SE", "OC", "NO", "DE", "" };
Using
DateTime value = new DateTime(2016, 3, 1);
// Formatting as usual but with custom format
String result = value.ToString("ddMMMyyyy", caFormat);
Outcome
01MR2016
I think you are refering to a Canadian standard, as explained here
.Net does not provide that conversion,but you can do something like this:
Dictionary<string, string> abbr = new Dictionary<string, string>() {
{"Jan","JA"},
{ "Feb","FE"},
{ "Mar","MR"},
{ "Apr","AL"},
{ "May","MA"},
{ "Jun","JN"},
{ "Jul","JL"},
{ "Aug","AU"},
{ "Sep","SE"},
{ "Oct","OC"},
{ "Nov","NO"},
{ "Dec","DE"}
};
string val = Convert.ToDateTime(DateTime.Now).ToString("ddMMMyyyy",
System.Globalization.CultureInfo.InvariantCulture);
var newstr = abbr.Aggregate(val, (current, value) =>
current.Replace(value.Key, value.Value));
value = Convert.ToDateTime(currentDate).ToString("ddMMyyyy",new CultureInfo("fr-FR"));
I don't think so that its having any solution but yeah you can try split() function and by splitting date after 2 digits of day + two letters of month and again merge the string, hope that will help you.
Related
I am trying to output a Hebrew calendar date in English with C#. The following outputs the date in Hebrew:
var ci = System.Globalization.CultureInfo.CreateSpecificCulture("he-IL");
ci.DateTimeFormat.Calendar = new System.Globalization.HebrewCalendar();
Response.Write(DateTime.Today.ToString("MMM d, yyyy", ci));
Response.Write(DateTime.Today.ToString("d-M-y", ci));
Gives
כסלו כ"ו, תשע"ה
כ"ו-ג'-תשע"ה
for December 18, 2014. Change the CultureInfo to "en-US" raises an "Not a valid calendar for the given culture." error. I am trying to get
26 Kislev 5775
and
26-09-5775
I could not figure out how to set the array of month names for leap years or the array of day numbers so that they are rendered as English numbers rather than hebrew letters. My solution was:
Globals.cs
public static string[] HebrewMonthNames =
{
"Tishrei",
"Cheshvan",
"Kislev",
"Tevet",
"Shevat",
"Adar",
"Nissan",
"Iyar",
"Sivan",
"Tamuz",
"Av",
"Elul"
};
public static string[] HebrewMonthNamesLeapYear =
{
"Tishrei",
"Cheshvan",
"Kislev",
"Tevet",
"Shevat",
"Adar I",
"Adar II",
"Nissan",
"Iyar",
"Sivan",
"Tamuz",
"Av",
"Elul"
};
Utils.cs
public string FormatHebrewDate(DateTime dtGregorian)
{
System.Globalization.HebrewCalendar hCal = new System.Globalization.HebrewCalendar();
string sDate = hCal.GetDayOfMonth(dtGregorian).ToString() + " ";
if (hCal.IsLeapYear(hCal.GetYear(dtGregorian)))
{
sDate += Globals.HebrewMonthNamesLeapYear[hCal.GetMonth(dtGregorian) - 1];
}
else
{
sDate += Globals.HebrewMonthNames[hCal.GetMonth(dtGregorian) - 1];
}
sDate += " " + hCal.GetYear(dtGregorian).ToString();
return sDate;
}
Option 1:
You can override the DateTimeFormatInfo.MonthNames and MonthGenitiveNames properties as well as their corresponding AbbreviatedMonthNames and AbbreviatedMonthGenitiveNames properties.
They are simple 1-dimensional string[] arrays and have a public setters, which allows you to add your custom translations to the CultureInfo:
When this property is set, the array must be one-dimensional and must
have exactly 13 elements. Calendar objects accommodate calendars with
13 months. The first element (the element at index zero) represents
the first month of the year defined by the Calendar property.
If you set the MonthNames property, you must also set the
MonthGenitiveNames property.
If the custom pattern includes the format pattern "MMMM",
DateTime.ToString displays the value of MonthNames in place of the
"MMMM" in the format pattern.
This property is affected if the value of the Calendar property
changes.
So you could modify your code example to this:
// I am just using German Number representations for the example.
// Use additional string Arrays to suit the abbrevated
// and the Genetive names.
// Replaye with whatever suits your needs.
string[] monthNames =
{
"Eins",
"Zwei",
"Drei",
"Vier",
"Fünf",
"Sechs",
"Sieben",
"Acht",
"Neun",
"Zehn",
"Elf",
"Zwölf",
string.Empty
};
// Assign each string Array to its corresponding property.
// I am using the same Array here just as an example for
// what is possible and because I am lazy... :-)
ci.DateTimeFormat.MonthNames = monthNames;
ci.DateTimeFormat.MonthGenitiveNames = monthNames;
ci.DateTimeFormat.AbbreviatedMonthNames = monthNames;
ci.DateTimeFormat.AbbreviatedMonthGenitiveNames = monthNames;
These names will then be used in with your format string in the output, just as you want it to have.
Each time you change the calendar, these overrides will be lost. So you need to make sure to re-assign the custom values if you need it.
[Update] Option 2:
A more persistent approach might be to use the CultureAndRegionInfoBuilder Class.
Defines a custom culture that is new or based on another culture and
country/region. The custom culture can be installed on a computer and
subsequently used by any application that is running on that computer.
You can either create a complete replacement version of the "he-IL" culture or create a variation with just your custom translations, or anything in between.
Using this approach you do not have to manually make sure that the translations are in place after each Culture-switch in the appliaction like in Option 1. Once the new Custom Culture is registered, you can use it like any other CultureInfo.
Please note that your application will need administrative priviledges to register a new Custom Culture.
The creation of a Custom Culture is not too complicated as the following code snippet shows.
Example from MSDN: CultureAndRegionInfoBuilder
The following example defines a custom ru-US culture that represents
the Russian language in the United States. The example defines the
custom culture by loading settings from the Russian (Russia)
CultureInfo object and the U.S. RegionInfo object, and then sets a
number of CultureAndRegionInfoBuilder properties. The example
registers the custom culture, and then instantiates it and makes it
the current thread culture.
using System;
using System.Globalization;
using System.Threading;
public class Example
{
public static void Main()
{
// Create a custom culture for ru-US.
CultureAndRegionInfoBuilder car1 = new CultureAndRegionInfoBuilder("ru-US",
CultureAndRegionModifiers.None);
car1.LoadDataFromCultureInfo(CultureInfo.CreateSpecificCulture("ru-RU"));
car1.LoadDataFromRegionInfo(new RegionInfo("en-US"));
car1.CultureEnglishName = "Russian (United States)";
car1.CultureNativeName = "русский (США)";
car1.CurrencyNativeName = "Доллар (США)";
car1.RegionNativeName = "США";
// Register the culture.
try {
car1.Register();
}
catch (InvalidOperationException) {
// Swallow the exception: the culture already is registered.
}
// Use the custom culture.
CultureInfo ci = CultureInfo.CreateSpecificCulture("ru-US");
Thread.CurrentThread.CurrentCulture = ci;
Console.WriteLine("Current Culture: {0}",
Thread.CurrentThread.CurrentCulture.Name);
Console.WriteLine("Writing System: {0}",
Thread.CurrentThread.CurrentCulture.TextInfo);
}
}
// The example displays the following output:
// Current Culture: ru-US
// Writing System: TextInfo - ru-US
I know this isn't an ideal answer, but you could manually input the list of Hebrew months, and use DateTime.Today.Month as an index into that list. Similarly, DateTime.Today.Day and .Year give integer output that you can use. Sorry, it seems a bit wrong to roll your own formatting, doesn't it?
You could still use string.format() to ensure it looks the way you want.
You can use this (I know it's not c#, but you should be able to get what I'm doing here):
Dim c As New CultureInfo("he-IL")
c.DateTimeFormat.Calendar.ToDateTime(Now.Year, Now.Month, Now.Day, Now.Hour, Now.Minute, Now.Second, Now.Millisecond).ToString("MMMM", New CultureInfo("en-GB"))
MessageBox.Show(c.DateTimeFormat.Calendar.ToDateTime(Now.Year, Now.Month, Now.Day, Now.Hour, Now.Minute, Now.Second, Now.Millisecond).ToString("MMMM", New CultureInfo("en-GB")))
But it will give you the Gregorian Calendar name (December)
piojo's suggestion to build up a dictionary object that contains the English version of the Hebrew name might work better
I do not believe that .NET has culture information that you want to use. However, you can create your own CultureInfo and modify the DateTimeFormat to suit your needs:
var cultureInfo = CultureInfo.CreateSpecificCulture("he-IL");
cultureInfo.DateTimeFormat.Calendar = new HebrewCalendar();
cultureInfo.DateTimeFormat.AbbreviatedMonthNames = new[] {
"Translation of תשרי",
"Translation of חשון",
// 11 more elements
};
cultureInfo.DateTimeFormat.AbbreviatedMonthGenitiveNames = new[] { ... };
cultureInfo.DateTimeFormat.MonthNames = new[] { ... };
cultureInfo.DateTimeFormat.MonthGenitiveNames = new[] { ... };
(Sorry for not providing the correct translations but I do not know Hebrew.)
You can then use this cultureInfo exactly as you do in your question.
If required you can also modify the day names in a similar fashion.
It is important that the calendar is set before modifying the various month and date name properties. The number of expected entries in the month name arrays changes as the calendar changes.
I have changed my system date format to Faeroese.
I want to convert DateTime to String according to customCulture with G format (combination of date and Time)
check the below code.
namespace TestDateConvertion
{
class Program
{
static void Main(string[] args)
{
object value = new DateTime(2003,12,23,6,22,30);
DateTime dateTimeValue = (DateTime)value;
CultureInfo customCulture = MySettings.getCustomCulture();
//for getting custom culture in my app
//in custom culture i have changed shortDateFormat according to the user preference.
//value in shortDateFormat = dd/MM/yyyy
string result = string.Format(customCulture, "{0:G}", result);
Console.WriteLine(result);
Console.ReadLine();
}
}
}
but i get the output with sepertators according to system DateTime not with users given format in customCulture,
i even dont find any method overloaded in string.Format() or DateTime.ToString() to do this.
If i pass CultureInfo.InvariantCulture then i cant get output in G format.
try this:
DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);
Console.WriteLine(date1.ToString("G", DateTimeFormatInfo.InvariantInfo));
// Displays 04/10/2008 06:30:00
Console.WriteLine(date1.ToString("G", CultureInfo.CreateSpecificCulture("en-us")));
// Displays 4/10/2008 6:30:00 AM
Console.WriteLine(date1.ToString("G", CultureInfo.CreateSpecificCulture("nl-BE")));
According to Standard Date and Time Format Strings "G" uses short date format (as you claim to specify). So most likely reason of using local culture separator is covered in The "/" Custom Format Specifier portion of ""Custom Date and Time Format Strings".
Since your "short date format" is "dd/MM/yyyy" than instead of "/" it will use corresponding separator from the culture info (which you are likely picking from default culture).
Escaping with \ is covered in the Using the escape character portion of the same "Custom Date and Time Format Strings" article.
So you want your shortDateFormat = #"dd\/MM\/yyyy" or properly specify DateTimeSeparator in corresponding part of your custom CultureInfo.
I am getting this: 9/13/2011 12:00:00 AM
from my DB and I want to show like this:
9/13/2011
This is my code for this:
litDate.Text = Obj1.DueDate.ToString();
My DueDate is of this property:
public DateTime? DueDate { get; set; }
Try this:
litDate.Text = Obj1.Date.ToString("MM/dd/yyyy");
Use the formatter "d", only if Obj1.Date is of type DateTime.
if(Obj1.DueDate.HasValue)
{
litDate.Text = Obj1.DueDate.Value.ToString("d");
}
http://msdn.microsoft.com/en-us/library/az4se3k1.aspx
This gives all the standard date format strings with examples.
Here is the example you want:
// Display using current (en-us) culture's short date format
DateTime thisDate = new DateTime(2008, 3, 15);
Console.WriteLine(thisDate.ToString("d"));
// Displays 3/15/2008
The answers that explicitly format the string should not be used in any case where you might have to internationalize the date. This answer uses the culture context of the user's computer.
litDate.Text = Obj1.Date.ToShortDateString();
Along with insta's answer, you can also use
litDate.Text = Obj1.Date.ToString("MM/dd/yyyy");
http://www.csharp-examples.net/string-format-datetime/
EDIT: Now that you revised your question to a COMPLETELY DIFFERENT datatype, you need to learn how Nullables work. Check .HasValue, and if so, then .Value will be a DateTime, making all the rest of these answers relevant again.
DateTime date = new DateTime(1970, 1, 15);
string sdate = date.ToString(value_i_will_forget as string,
CultureInfo.InvariantCulture);
// some lines later
string format_string = MagicParse(sdate,
CultureInfo.InvariantCulture);
I have an arbitrary date that I write to a string with CulturInfo.InvariantCulture. The .Net format I use - "d", for example - is now forgotten.
I do know however that the string hasn't changed, its still valid and its still with invariant culture. Im looking for the MagicParse function to extract the format string used to write the formatted date.
Unless you have a sample of dates in which the day exceeds 12, then there is no feasible way that this would ever be safe.
DateTime.Parse(your_date_string, CultureInfo.InvariantInfo)
, also you can add specific DateTimeStyles in third parameter
Try this one
http://msdn.microsoft.com/en-US/library/system.globalization.datetimeformatinfo.shortdatepattern.aspx
I am trying to convert my string formatted value to date type with format dd/MM/yyyy.
this.Text="22/11/2009";
DateTime date = DateTime.Parse(this.Text);
What is the problem ?
It has a second override which asks for IFormatProvider. What is this? Do I need to pass this also? If Yes how to use it for this case?
Edit
What are the differences between Parse and ParseExact?
Edit 2
Both answers of Slaks and Sam are working for me, currently user is giving the input but this will be assured by me that they are valid by using maskTextbox.
Which answer is better considering all aspects like type saftey, performance or something you feel like
Use DateTime.ParseExact.
this.Text="22/11/2009";
DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", null);
You need to call ParseExact, which parses a date that exactly matches a format that you supply.
For example:
DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
The IFormatProvider parameter specifies the culture to use to parse the date.
Unless your string comes from the user, you should pass CultureInfo.InvariantCulture.
If the string does come from the user, you should pass CultureInfo.CurrentCulture, which will use the settings that the user specified in Regional Options in Control Panel.
Parsing a string representation of a DateTime is a tricky thing because different cultures have different date formats. .Net is aware of these date formats and pulls them from your current culture (System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat) when you call DateTime.Parse(this.Text);
For example, the string "22/11/2009" does not match the ShortDatePattern for the United States (en-US) but it does match for France (fr-FR).
Now, you can either call DateTime.ParseExact and pass in the exact format string that you're expecting, or you can pass in an appropriate culture to DateTime.Parse to parse the date.
For example, this will parse your date correctly:
DateTime.Parse( "22/11/2009", CultureInfo.CreateSpecificCulture("fr-FR") );
Of course, you shouldn't just randomly pick France, but something appropriate to your needs.
What you need to figure out is what System.Threading.Thread.CurrentThread.CurrentCulture is set to, and if/why it differs from what you expect.
Although the above solutions are effective, you can also modify the webconfig file with the following...
<configuration>
<system.web>
<globalization culture="en-GB"/>
</system.web>
</configuration>
Ref : Datetime format different on local machine compared to production machine
You might need to specify the culture for that specific date format as in:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB"); //dd/MM/yyyy
this.Text="22/11/2009";
DateTime date = DateTime.Parse(this.Text);
For more details go here:
http://msdn.microsoft.com/en-us/library/5hh873ya.aspx
Based on this reference, the next approach worked for me:
// e.g. format = "dd/MM/yyyy", dateString = "10/07/2017"
var formatInfo = new DateTimeFormatInfo()
{
ShortDatePattern = format
};
date = Convert.ToDateTime(dateString, formatInfo);
After spending lot of time I have solved the problem
string strDate = PreocessDate(data);
string[] dateString = strDate.Split('/');
DateTime enter_date = Convert.ToDateTime(dateString[1]+"/"+dateString[0]+"/"+dateString[2]);
private DateTime ConvertToDateTime(string strDateTime)
{
DateTime dtFinaldate; string sDateTime;
try { dtFinaldate = Convert.ToDateTime(strDateTime); }
catch (Exception e)
{
string[] sDate = strDateTime.Split('/');
sDateTime = sDate[1] + '/' + sDate[0] + '/' + sDate[2];
dtFinaldate = Convert.ToDateTime(sDateTime);
}
return dtFinaldate;
}
use this to convert string to datetime:
Datetime DT = DateTime.ParseExact(STRDATE,"dd/MM/yyyy",System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat)
Just like someone above said you can send it as a string parameter but it must have this format: '20130121' for example and you can convert it to that format taking it directly from the control. So you'll get it for example from a textbox like:
date = datetextbox.text; // date is going to be something like: "2013-01-21 12:00:00am"
to convert it to: '20130121' you use:
date = date.Substring(6, 4) + date.Substring(3, 2) + date.Substring(0, 2);
so that SQL can convert it and put it into your database.
Worked for me below code:
DateTime date = DateTime.Parse(this.Text, CultureInfo.CreateSpecificCulture("fr-FR"));
Namespace
using System.Globalization;
You can use also
this.Text = "22112009";
DateTime newDateTime = new DateTime(Convert.ToInt32(this.Text.Substring(4, 4)), // Year
Convert.ToInt32(this.Text.Substring(2,2)), // Month
Convert.ToInt32(this.Text.Substring(0,2)));// Day
Also I noticed sometimes if your string has empty space in front or end or any other junk char attached in DateTime value then also we get this error message