Convert month int to month name - c#

I was simply trying to use the DateTime structure to transform an integer between 1 and 12 into an abbrieviated month name.
Here is what I tried:
DateTime getMonth = DateTime.ParseExact(Month.ToString(),
"M", CultureInfo.CurrentCulture);
return getMonth.ToString("MMM");
However I get a FormatException on the first line because the string is not a valid DateTime. Can anyone tell me how to do this?

CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(1);
See Here for more details.
Or
DateTime dt = DateTime.Now;
Console.WriteLine( dt.ToString( "MMMM" ) );
Or if you want to get the culture-specific abbreviated name.
GetAbbreviatedMonthName(1);
Reference

var monthIndex = 1;
return month = DateTimeFormatInfo.CurrentInfo.GetAbbreviatedMonthName(monthIndex);
You can try this one as well

You can do something like this instead.
return new DateTime(2010, Month, 1).ToString("MMM");

CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(
Convert.ToInt32(e.Row.Cells[7].Text.Substring(3,2))).Substring(0,3)
+ "-"
+ Convert.ToDateTime(e.Row.Cells[7].Text).ToString("yyyy");

Related

Can i convert a string in format Mddyyy to datetime object c# core

I trying to parse a string like 4212021 where 4 is the month, 21 is the day, and 2021 is the year, into a DateTime object. I've tried using the following code but for some reason I am getting 'String '4212021' was not recognized as a valid DateTime.':
string datetimestring = "4122021";
var date = DateTime.ParseExact(datetimestring, "Mddyyyy", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal);
All help is appreciated. Thanks.
This doesn't work without date separators. So you could add them:
string format = "Mddyyyy";
CultureInfo culture = CultureInfo.InvariantCulture;
string separator = culture.DateTimeFormat.DateSeparator;
if(datetimestring.Length >= format.Length)
{
int firstIndex = datetimestring.Length % 2 == 0 ? 2 : 1;
datetimestring = datetimestring.Insert(firstIndex, separator);
datetimestring = datetimestring.Insert(firstIndex + 2 + separator.Length, separator);
}
DateTime date = DateTime.Parse(datetimestring, culture, DateTimeStyles.None);
This works also if the month has two digits like in "12122021".
Another, maybe simpler way was to use ParseExact with "Mddyyyy HHmmss" and append zero time:
datetimestring = datetimestring + " 000000"; // check first length ofc
DateTime date = DateTime.ParseExact(datetimestring, "Mddyyyy HHmmss", culture, DateTimeStyles.None);
It's just the "M" modificator that does not work if you use it without separators AND with variable length. If you ensure leading zeros, it should work. ("04" instead of "4")
string datetimestring = 4122021.ToString("D8");
var date = DateTime.ParseExact(datetimestring, "Mddyyyy", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal);
Since your day is always 2 digits (dd) you can just append a 0 to the start of the string when the month only has 1 digit, and use the MM for month:
string datetimestring = "4122021";
var date = DateTime.ParseExact(datetimestring.PadLeft(8,'0'), "MMddyyyy", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal);
I am imagining you have a special reason for not changing the input. You can try this way, it will work.
string datetimestring = "4122021";
var date = DateTime.ParseExact(datetimestring.Length < 8 ? $"0{datetimestring}" : datetimestring, "Mddyyyy", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal);
See if it is appropriate for your context?

How to convert date to 'ccyymmddhhmmss' format?

How to convert date to 'ccyymmddhhmmss' format in c#?
You might want to try this... I don't know if cc is included, so I solved for the cc.
DateTime time = DateTime.Now;
string format = "yyMMddhhmmss";
Console.WriteLine(((Convert.ToInt32(time.ToString("yyyy")) / 100) + 1).ToString() + time.ToString(format));
For "yyMMddhhmmss".....Try this...And don't forget that capital M is Month and lower case m is minutes.
DateTime dt = Convert.ToDateTime("8 Oct 10 19:00");
Console.WriteLine(dt.ToString("yyMMddhhmmss"));
From what I understand from your question, you want to format a c# date object to the specified format?
The easiest way to do that is by using the date.ToString("yyyyMMddHHmmss") - where date is the Date Object... There are several choices to this - like having 12-hour instead of 24-hour etc. The best option is to read through http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx and set what you need.
Hope this helps.
#Chris_techno25: I took the freedom to extend your answer:
If we stick to the question of Narashima, he wants the format ccyymmddhhmmss.
So I've scratched up this extension method:
public static string IncludeCentury(this DateTime sourceDate, bool replace)
{
var source = String.Format("{0}/{1}", sourceDate.Year / 100 + 1, sourceDate);
if(replace)
return Regex.Replace(source, "[^0-9]", "");
else
return source;
}
Usage:
var includingCentury = DateTime.Now.IncludeCentury(true)
var includingCentury = DateTime.Now.IncludeCentury(false)
Output:
21218201491410
21/2/18/2014 9:18:10 AM

Error: No overload for method "ToString" takes 1 arguments

I am trying to format date in a specific order
Time = DateTime.Parse(p.Time.ToString("dd-MM-yyyy HH:mm:ss"))
Data type of Time is DateTime
But i am getting this error:
No overload for method "ToString" takes 1 arguments.
p is the object of the table from which i am getting Time.
List<ProductImageMapWrapper> lstpm = new List<ProductImageMapWrapper>();
lstpm = _db.ProductImageMaps.Where(i => i.ClientId == null && i.BrandId == null).Select(p => new ProductImageMapWrapper
{
Time= // Problem here
}
Now, I tried using it this way
Time = DateTime.Parse(string.Format("{dd-MM-yyyy HH:mm:ss}", p.Time))
but then i got this error:
LINQ to Entities does not recognize the method System.DateTime Parse(System.String) method, and this method cannot be translated into a store expression.
String Time = Convert.ToDateTime(p.Time).ToString("dd-MM-yyyy HH:mm:ss");
It looks to me like the Time property of both types (ProductImageMap and ProductImageMapWrapper) is a DateTime. If that is true, then you should use Time = p.Time
There's a common misconception that a DateTime value somehow has a format. Actually, you apply a given format when you convert the DateTime value into a string. To copy a DateTime value from one place to another, just assign it.
parenthesis are in the wrong place. You cannot parse it as that format. You have to parse P, then format as the string.
DateTime.Parse(System.DateTime.Now).ToString("dd-MM-yyyy HH:mm:ss")
Here is the example how to parse date from string and you can correct this for your structure to work:
string p = "21-11-2013 11:12:13";
DateTime time = DateTime.ParseExact(p, "dd-MM-yyyy HH:mm:ss", System.Globalization.CultureInfo.CurrentCulture);
Considering p.Time as string value in the date format you suggested, I think you want to parse string to DateTime as,
CultureInfo provider = CultureInfo.InvariantCulture;
string format = "dd-MM-yyyy HH:mm:ss"; //This should be format that you get in string
List<ProductImageMapWrapper> lstpm = new List<ProductImageMapWrapper>();
lstpm = _db.ProductImageMaps.Where(i => i.ClientId == null && i.BrandId == null).Select(p => new ProductImageMapWrapper
{
Time = DateTime.ParseExact(p.Time, format, provider)
});
Might Help
var selectQuery=from add in db.address
select add.myDate.toString("{0:dddd, MMMM d, yyyy}");
selectQuery.Distinct();
Normal Convers.
DateTime time = DateTime.Now; // Use current time
string format = "MMM ddd d HH:mm yyyy"; // Use this format
Console.WriteLine(time.ToString(format));
1.MMM display three-letter month
2.ddd display three-letter day of the WEEK
3.d display day of the MONTH
4.HH display two-digit hours on 24-hour scale
5.mm display two-digit minutes
6.yyyy displayfour-digit year
You want to use DateTime.ToString(format) not Nullable.ToString(no
overload):
DateTime? myDate = form.dteStartDate;
string sqlFormattedDate = myDate.Value.ToString("yyyy-MM-dd HH:mm:ss");
Of course this doesn't handle the case that there is no value. Perhaps something like this:
string sqlFormattedDate = myDate.HasValue
? myDate.Value.ToString("yyyy-MM-dd HH:mm:ss")
: "<not available>";

Parse date format to DateTime c#

How to parse this string:
"\"2014-01-02T23:00:00.000Z\"" to DateTime
This didn't work:
DateTime? dateTimeFormat= string.IsNullOrEmpty(inputString) ?? (DateTime?)null : DateTime.Parse(inputString);
You need to specify exact format of you datetime to the DateTime.ParseExact method:
string input = "\"2014-01-02T23:00:00.000Z\"";
var date = DateTime.ParseExact(input, "'\"'yyyy-MM-dd'T'HH:mm:ss.fff'Z\"'", null);
Description of format provided:
'\"' - match first "
yyyy-MM-dd - match 2014-01-02
'T' - match T
HH:mm:ss.fff - match 23:00:00.000
'Z\"' - match Z"
This will help
string test = "2014-01-02T23:00:00.000Z";
DateTime dt = Convert.ToDateTime(test);
DateTime.ParseExact(your_date.ToString(), "yyyy-MM-ddTHH:mm:ssZ", null)
Reformat the string to put in the proper format, then parse
string = "\"2014-01-02T23:00:00.000Z\"";
string = substring(3,10) + " " + substring(14,8); //"2014-01-02 23:00:00"
time = DateTime.Parse(string);
Try This:
DateTime.ParseExact("2014-01-02T23:00:00.000Z" , "yyyy-MM-DDThh:mm:ssZ",CultureInfo.InvariantCulture);
Maybe this might work.
Add-
using System.Globalization;
I've tried almost all of the method/codes in this answer but none of them worked for me. Although, using parts of code of previous answer to this question, I did this and it worked perfectly for me.
var d = "2019-01-11T05:00:00.000Z"; //Date
int year = Convert.ToInt32(d.Substring(0, 4));
int month = Convert.ToInt32(d.Substring(5, 2));
int day = Convert.ToInt32(d.Substring(8, 2));
var time = new DateTime(year, month, day);
I was not concerned with the time. You can add it if you want.

String To DateFormat Conversion

Is there any way I don't have to specify the number of digits in day/month/year?
For e.g 1/2/1991
I want a method which satisfies both 1/2/1991,11/3/1990,12/12/1991
I don't know how many digits will be there in either month, year, or days.
My code is
string copy = splittedData[0] + splittedData[1] + splittedData[2];//date+month+year
DateTime datetime = DateTime.ParseExact(copy, "ddMMyyyy", CultureInfo.InvariantCulture);
DateTime dateAndTime = datetime;
The problem is the number of digits in splitted data array are not known to me and thus the above format "ddMMyyyy" give me exception on some cases.
Since you already have the day month and year then just create a date with the three of them like so;
DateTime date = new DateTime(year, month, day);
No parsing is necessary. You already have all the fields you want to create the date, and you dont need to put it into a special format to create a date.
If you are not sure the if the input is valid, then wrap the creation in a try/catch block to catch an ArgumentOutOfRangeException should it should occur.
Since you updated your question with the code you have, you can concatenate date components with a separator like:
string copy = splittedData[0] + "/" + splittedData[1] + "/" + splittedData[2];
Later you can do:
DateTime dt = DateTime.ParseExact(copy, "d/M/yyyy", CultureInfo.InvariantCulture);
I used the format "d/M/yyyy" with single d and M which would account for both single/double digit day/month.
So it will work for dates like:
01/01/2013
1/01/2013
22/09/2013
02/9/2013
DateTime.ParseExact is specifically intended to not allow what you are asking for. DateTime.Parse will allow it, though.
You say you have the 3 parts as separate strings -- if you insert the /'s and parse, it should succeed (InvariantCulture expects the order month-day-year):
string datetimeString = string.Join("/", new[] {month, day, year});
DateTime datetime = DateTime.Parse(datetimeString, CultureInfo.InvariantCulture);
Or you could convert them to integers and construct a DateTime directly:
DateTime datetime = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), Convert.ToInt32(day));
What #n00b said. You've already got the individual components of the date: why are you globbing them back together just so you can call DateTime parsing routines? Just do something like this:
private static DateTime StringToDateTime( string year , string month , string day )
{
int yyyy = int.Parse(year) ;
int mm = int.Parse(month) ;
int dd = int.Parse(day) ;
DateTime dt = new DateTime(yyyy,mm,dd) ;
return dt ;
}
As an added bonus, The above code will probably run faster than DateTime.Parse() or DateTime.ParseExact().

Categories

Resources