I'm using "yyyy-MM-dd" several time in the code for date formatting
For example :
var targetdate = Date.ToString("yyyy-MM-dd");
Is it possible to declare the format as constant, so that use of the code again and again can be avoided
Use an extension method without declare any format again and again like this:
public static class DateExtension
{
public static string ToStandardString(this DateTime value)
{
return value.ToString(
"yyyy-MM-dd",
System.Globalization.CultureInfo.InvariantCulture);
}
}
So you use it in this way
var targetdate = Date.ToStandardString();
Use this as
const string dateFormat = "yyyy-MM-dd";
//Use
var targetdate = Date.ToString(dateFormat);
OR
//for public scope
public static readonly string DateFormat = "yyyy-MM-dd";
//Use
var targetdate = Date.ToString(DateFormat);
//from outside the class, you have to use in this way
var targetdate = Date.ToString(ClassName.DateFormat);
Another option that you can do is use the DateTimeFormatInfo overload on .ToString(...) rather than the string overload.
public static readonly System.Globalization.DateTimeFormatInfo MyDateTimeFormatInfo
= new System.Globalization.DateTimeFormatInfo()
{
ShortDatePattern = "yyyy-MM-dd",
LongTimePattern = "",
};
Now you can do var targetdate = DateTime.Now.ToString(MyDateTimeFormatInfo); which is much the same as using string, but you have a lot more control over many other formatting properties.
Related
Here I want to convert date into string using tostring but when I convert it back, (string to datetime), the format is different.
static void Main(string[] args)
{
string cc = "2014/12/2";
DateTime dt = DateTime.Parse(cc);
Console.WriteLine(dt);
Console.ReadLine();
}
expected output:
2014/12/2
But I get:
12/2/2014
string DateString = "06/20/1990";
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime dateVal = DateTime.ParseExact(DateString, "yyyy-MM-dd", culture);
This will be your desire output
udpated
string DateString = "20/06/1990";;
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime dt = DateTime.ParseExact(DateString,"dd/mm/yyyy",culture);
dt.ToString("yyyy-MM-dd");
Call ToString with format provided when you convert DateTime instance back to string:
Console.WriteLine(dt.ToString(#"yyyy/M/d");
try this
DateTime dt = DateTime.ParseExact(dateString, "ddMMyyyy",
CultureInfo.InvariantCulture);
dt.ToString("yyyyMMdd");
use this:
string cc = "2014/12/2";
DateTime dt = DateTime.Parse(cc);
string str = dt.ToString("yyyy/M/dd"); // 2014/12/02 as you wanted
Console.WriteLine(str);
Console.ReadLine();
As you can read here, DateTime.ToString() uses CurrentCulture to decide how to format its output (CurrentCulture of type CultureInfo provides information on how to format dates, currency, calendar etc. It is called locale in C++).
Thus, the simlplest solution as suggested by previous answers, is to use an overload of ToString() which accepts a format string, effectively overriding the CurrentCulture info:
dt.ToString(#"yyyy/MM/dd");
More on datetime formatting can be found here.
you can use
string formattedDate= dt.ToString("yyyy/M/d");
For reverse you can use
DateTime newDate = DateTime.ParseExact("2014/05/22", "yyyy/M/d", null);
So if your expected output is like : 2014/12/2
you have to use
newDate.ToString("yyyy/M/d");
This is simple, You just need to use date pattern during display
string cc = "2014/12/2";
string datePatt = #"yyyy/MM/d";
DateTime dt = Convert.ToDateTime(cc);
Console.WriteLine(dt.ToString(datePatt));
What is an elegant way to pull out common formats (e.g. datetime) for string.format into accessible constants?
Ideally I would like to do something like the following, but I get the below error when I try to use this code.
var now = DateTime.Now;
var format = "yyyy-MM-dd";
Console.WriteLine(string.Format("The date is {1:{0}}", format, now));
[System.FormatException: Input string was not in a correct format.]
at Program.Main(): line 9
The reasoning behind this is that certain API's require a specific datetime format. I would like to be able to reference a single place to get that format, such that all or none of the calls will work.
I realize that the following will work, but it doesn't seem very elegant.
Console.WriteLine(string.Format("The date is {1:" + format + "}", format, now));
You could go an app constant route - a static class that holds your format strings.
namespace App.Framework {
public static class AppConstant {
public static readonly string DisplayDateShort = "MM/dd/yyyy";
}
}
As far as your example goes, it's kind of flawed; you want to call ToString() on your DateTime value.
Console.WriteLine(now.ToString(AppConstant.DisplayDateShort));
You can find all the used format strings under DateTimeFormatInfo.CurrentInfo.GetAllDateTimePatterns().
Afterwards you can individually try to parse your input data with each value and see which on returns true (see: DateTime.TryParseExact()).
Console.WriteLine (DateTimeFormatInfo.CurrentInfo.GetAllDateTimePatterns());
Sample code:
void Main()
{
var now = DateTime.Now.ToString();
foreach(var format in DateTimeFormatInfo.CurrentInfo.GetAllDateTimePatterns()){
DateTime result;
if(DateTime.TryParseExact(now, format, CultureInfo.CurrentCulture, DateTimeStyles.None, out result)){
Console.WriteLine(string.Format("The date is {0}, the format is: {1}", result, format));
}
}
}
You could consider pushing the format into an extension method that could be consumed as needed, i.e.:
public static class DateExt
{
public static string FormatAsSomething( this DateTime dt )
{
string format = "yyyy-MM-dd";
string result = dt.ToString( format );
return result;
}
}
And then:
var now = DateTime.Now;
Console.WriteLine( "The date is {0}", now.FormatAsSomething() );
Whenever the format needs to be updated, simply update the extension method.
You can use custom format provider for DateTime values:
static void Main(string[] args)
{
var now = DateTime.Now;
var str = string.Format(new MyDateFormatter(), "The date is {0}", now);
Console.WriteLine(str);
MyDateFormatter.DefaultDateFormat = "dd-MM-yyyy HH:mm";
str = string.Format(new MyDateFormatter(), "The date is {0}", now);
Console.WriteLine(str);
}
public class MyDateFormatter: IFormatProvider, ICustomFormatter
{
public static string DefaultDateFormat = "yyyy-MM-dd";
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return this;
return null;
}
public string Format(string format, object arg, IFormatProvider formatProvider)
{
// Check whether this is an appropriate callback
if (!this.Equals(formatProvider))
return null;
var argFormat = "{0:" + (arg is DateTime ? DefaultDateFormat : string.Empty) + "}";
return string.Format(argFormat, arg);
}
}
in my code i can get 2 types of string that represents dateTime:
1."2013-09-05T15:55"
2."09-05T19:10"
How do i convert it to a valid DateTime?
i tried the following code but it throws an exception for the second format:
String departureDateStr = "09-05T19:10";
DateTime dt = Convert.ToDateTime(departureDateStr);
how do i convert the second type of string to a valid DateTime ?
do i need some kind of string manipulation?
thx,
Amir
DateTime.TryParseExact has an overload that allows you to pass multiple formats as an array. Each date string is then compared with the various formats within the array so you don't need to know ahead of time which format to look for.
string d1 = "2013-09-05T15:55";
string d2 = "09-05T19:10";
string[] formats = new string[] { "yyyy-MM-ddTHH:mm", "MM-ddTHH:mm" };
List<string> dates = new List<string>() { d1, d2 };
foreach (string date in dates)
{
DateTime dt;
if (DateTime.TryParseExact(date, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
//dt successfully parsed
}
}
TryParseExact also returns false instead of throwing an exception if none of the formats in the array matched the input.
Use DateTime.ParseExact method with custom datetime format string:
string departureDateStr = "09-05T19:10";
string departureDateStr2 = "2013-09-05T19:10";
var dt = DateTime.ParseExact(departureDateStr, "MM-ddTHH:mm", System.Globalization.CultureInfo.InvariantCulture);
var dt2 = DateTime.ParseExact(departureDateStr2, "yyyy-MM-ddTHH:mm", System.Globalization.CultureInfo.InvariantCulture);
or universal call for both formats:
var dt = DateTime.ParseExact(departureDateStr, new[] { "MM-ddTHH:mm", "yyyy-MM-ddTHH:mm" }, System.Globalization.CultureInfo.InvariantCulture);
You can use DatetIme.ParseExact() method for this. It converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.
String departureDateStr = "09-05T19:10";
IFormatProvider provider = System.Globalization.CultureInfo.InvariantCulture;
string format = "MM-ddTHH:mm";
DateTime parsedDate = DateTime.ParseExact(departureDateStr, format, provider);
If you need this conversion a lot of times, then you can even make it an extension method as below:
public static class StringExtensions
{
public static DateTime ToDate(this string str)
{
IFormatProvider provider = System.Globalization.CultureInfo.InvariantCulture;
string format = "MM-ddTHH:mm";
return DateTime.ParseExact(str, format, provider);
}
}
I have a string that is formatted as YYYYMMDD - how can i make a copy in the format YYYY-MM-DD?
// this is your original string
string _str = "20130101";
// you need to convert it to valid DateTime datatype
// so you can freely format the string to what you want
DateTime _date = DateTime.ParseExact(_str, "yyyyMMdd", CultureInfo.InvariantCulture);
// converting to your desired format, which is now a string
string _dateStr = _date.ToString("yyyy-MM-dd");
DateTime.ParseExact()
You'll have to parse the DateTime, then reformat it:
var input = ...
var inFormat = "yyyyMMdd";
var outFormat = "yyyy-MM-dd";
var date = DateTime.ParseExact(inFormat, input, CultureInfo.InvariantCulture);
var output = date.ToString(outFormat);
the safe approach is to convert it to DateTime Object , for example in .Net using below function :
DateTime.TryParseExact()
and then using the DateTime Object you can format it again. like below example :
dateTimeObject.ToString(YourFormatInString);
check MSDN for more details : http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
I am using the Vimeo API and I want to convert the string <upload_date> to a short date format, {0:d} or {0:dd/mm/yyyy}.
This is my code but it doesn't seem to be working for me.
select new VimeoVideo
{
Date = String.Format("{0:d}",(item.Element("upload_date").Value)),
};
return Vids.ToList();
}
public class VimeoVideo
{
public string Date { get; set; }
}
As Oleg suggested you can try to parse your value to DateTime and then format it (use try catch if needed). That should work (not 100% sure since I don't know what item's type is).
var myDate = DateTime.Parse(item.Element("upload_date").Value);
Date = String.Format("{0:d}", myDate);
http://msdn.microsoft.com/it-it/library/1k1skd40(v=VS.80).aspx
Just verify the type of the Value property.. The above string formatter works for System.DateTime structure.. I assume in your case its string type object. According to the given sample date time string i have written this code.. Try out this.
CultureInfo provider = CultureInfo.InvariantCulture;
var format = "yyyy-MM-dd HH:mm:ss";
var dt = DateTime.ParseExact(item.Element("upload_date").Value, format, provider);
Date = string.Format("{0:d}", dt);
Hope it works..