Remove leading zero form month C# - c#

I'm having trouble to remove the leading zero from a date I found this on the miscrosoft website.
DateTime date1 = new DateTime(2008, 8, 18);
Console.WriteLine(date1.ToString("(M) MMM, MMMM",
CultureInfo.CreateSpecificCulture("en-US")));
// Displays (8) Aug, August
Totally doesn't work here.
This is my code:
string date = '2013-04-01'
DateTime billrunDate = Convert.ToDateTime(date);
string test = billrunDate.ToString("M");
Test is now 01 April
I just need it to be 4 in a string or int idc
Thanks!
Edit if I do:
billrunDate.ToString("(M)");
I get (4), but I dont need ()
EDIT 2:
Well this works
string test = billrunDate.ToString(" M ");
string testTwo = test.Trim();
Very very ugly

It's interpreting M as a standard date and time format for "month day pattern".
To interpret a single character pattern as a custom date and time pattern, just prefix it with %:
string test = billrunDate.ToString("%M");

One of my most referenced MSDN pages is the Custom Date & Time Format Strings page. You can use these as part of the formatting passed in to the ToString() method. If any of them are standard formatting patterns (as "M" is) and you want to use them along, you have to preface them with '%' or have a space before or after them in the format string (so use "%M", " M", or "M " instead of "M").
Relevant section:
"M"
The month, from 1 through 12.
"MM"
The month, from 01 through 12.
"MMM"
The abbreviated name of the month.
"MMMM"
The full name of the month.

You don't need to convert to string the date to retrieve the month number.
Just read the Month property of the DateTime class:
string date = "2013-04-01";
DateTime billrunDate = Convert.ToDateTime(date);
string test = billrunDate.Month.ToString();

Related

How to Create a Text Filename with DateTime using C#

I want to create a Filename with DateTime.Now to store the errors that catched using Exception Handling everyday.
I used DateTime.ToFileTime, but the format appending for not in date format.
string result = "myFile_" + DateTime.Now.ToFileTime() + ".txt";
string path = "E:\\ErrorCollector\\ErrorCollector" + DateTime.Now.ToFileTime()+ ".txt";
FileStream fi = new FileStream(path, FileMode.OpenOrCreate);
StreamWriter sw1 = new StreamWriter(fi);
sw1.WriteLine(DateTime.Now + "" + ex.message);
I am Expecting the filename like "ErrorCollector17/08/2019"
You are not allowed to create filename which contains any of following characters: /:*?"<>| on Windows, you can do like this
string path = "E:\\ErrorCollector\\ErrorCollector" + DateTime.Now.ToString("dd-MM-yyyy")+ ".txt"
You can try to use ToString function with a format.
DateTime.Now.ToString("dd/MM/yyyy",new System.Globalization.CultureInfo("en-US"));
c# online
As Soundararajan say I would suggest you use
"ddMMyyyy"
or
"dd-MM-yyyy"
due to the system will confuse your path contain \
shortest answer would be the code below:
DateTime.Now.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture);
DateTime.Now gets the current date and time based on your computer's clock.
.ToString(...) converts the DateTime object into a string with optional formatting inside as parameters.
"yyyyMMddHHmmss" is a pattern for how you want the DateTime object be mapped in a string manner where. assuming your computer's clock is currently ticked at "August 8, 2019 12:34:56 PM", then:
yyyy = is a 4 digit year as 2019
MM = is a 2 digit month equivalent such as 08
dd = is a 2 digit day of the year such as 08
HH = is a 2 digit hour equivalent in 24 Hours format such as 12
mm = is a 2 digit minute such as 34
ss = is a 2 digit second such as 56
and the output would be 20190808123456. Note that the arrangement of year, month, date, hour, minute, or even second can be in no specific order.
CultureInfo.InvariantCulture is used if you are formatting or parsing a string that should be parseable by a piece of software independent of the user's local settings (via source)
note that we removed special characters separating different parts of the DateTime object to prevent issues when filenames on Windows.

C# build date as string with leading 0s and no separators

I have a date. I would like to read out all the date parts into separate strings with leading 0s where applicable and then concatenate them to create a date string that is just numbers without any separators.
For example:
DateTime dt = DateTime.Now;
string year = dt.Year.ToString();
string month = dt.Month.ToString();
string day = dt.Day.ToString();
string hour = dt.Hour.ToString();
string minutes = dt.Minute.ToString();
string seconds = dt.Second.ToString();
string finalDt = string.Concat(year, month, day, hour, minutes, seconds);
I would like month to be 01 if it is January, day to be 03 if it is the third day, and likewise with hour, year, seconds. Is there a way to accomplish that without having to check the count for each datepart and pad it with a leading 0?
If there is a better way to accomplish what I'm trying to do overall, then I would like suggestions.
You can use DateTime.ToString(string format) for this purpse:
dt.ToString("yyyyMMddHHmmss")
Or if you still want to do each part separately:
string year = dt.Year.ToString("0000");
string month = dt.Month.ToString("00");
string day = dt.Day.ToString("00");
string hour = dt.Hour.ToString("00");
string minutes = dt.Minute.ToString("00");
string seconds = dt.Second.ToString("00");
What about using custom format-string in the DateTime.ToString method:
DateTime.Now.ToString("yyyyMMddhhmmss");
The DateTime type supports many ways of formatting, so you can build up the resulting format from individual "components". Refer to the Docs to see all the options available.

regular expression using C# to find a date

I try to use regular expression to find a date and time from a log file that looks like this:
Dec 25 14:11:03....
what is the best way to find them in log file and calculate the date and time
to an absolute value?
I am trying this code but it doesn't find the expression:
public long getDateAndgetTimeFromLog(TypeOfProtocols type, string lineOfLog)
{
long dnt = 0; //variable from date and time.
switch (type)
{
case TypeOfProtocols.PlinkSnifer:
if (Regex.IsMatch(lineOfLog, #"\d{2}:\d{2}:d{2}"))
{
}
break;
}
return dnt;
}
First: your pattern is invalid:
#"\d{2}:\d{2}:d{2}"
it must be:
#"\d{2}:\d{2}:\d{2}"
you missed one backslash \ before the last d
Second: I guess by absolute value you mean the long dnt variable? If so then you need to parse the date by using one of the overloads and get the DateTime.Ticks.
For example like this:
string dateString = "Dec 25 14:11:03";
DateTime date = DateTime.ParseExact(dateString, "MMM dd HH:mm:ss", CultureInfo.InvariantCulture);
long ticks = date.Ticks;
where:
MMM The abbreviated name of the month.
dd The day of the month, from 01 through 31.
HH The hour, using a 24-hour clock from 00 to 23.
mm The minute, from 00 through 59.
ss The second, from 00 through 59.
Custom Date and Time Format Strings
Third: your current pattern cannot find and capture the entire timestamp so you'll need to extend it to get the date and time parts in one string:
string logLine = "Dec 25 14:11:03 Hello world!";
// Your new pattern:
string pattern = #"([a-z]{3} \d{2} \d{2}:\d{2}:\d{2})";
Match match = Regex.Match(logLine, pattern, RegexOptions.IgnoreCase);
if (match.Success)
{
string dateFormat = "MMM dd HH:mm:ss";
string dateString = match.Groups[1].Value;
DateTime date = DateTime.ParseExact(dateString, dateFormat, CultureInfo.InvariantCulture);
long ticks = date.Ticks;
}
Currently you are only checking whether a log line contains a timestamp. I've added a () catching group to the pattern so you can use the cought value match.Groups[1].Value for parsing if a match was found. The index is 1 because there is only one group defined in the pattern. Group at the index 0 always contains the original string (the entire log line in this case).

I want to covert julian date(YYJJJ format) to any normal date format(MMDDYY) using c#. Is there any defined function for that?

Hi I have julian date string YYJJJ format. eg 05365(31st dec 2005). I want to covert to MMDDYY format(123105).
Is there any defined function for that in?
I faced same problem as I was try to convert dates from BACS 18 standard to a String. I couldn't find ready solution to this problem so I wrote this function:
private String bacsDateConvert(String bacsFormatDate)
{
int dateYear = Convert.ToInt16(bacsFormatDate.Substring(1, 2));
int dateDays = Convert.ToInt16(bacsFormatDate.Substring(3, 3));
DateTime outputDate = new DateTime();
outputDate = Convert.ToDateTime("31-12-1999");
outputDate = outputDate.AddYears(dateYear);
outputDate = outputDate.AddDays(dateDays);
String outputString = outputDate.ToString("yyyyMMdd");
return outputString;
}
//You may call it like this:
textBox4.Text = Convert.ToString(bacsDateConvert(bacsTxnValueDate));
You also may modify it slightly and easily make it return DateTime data type if you want to. I just needed to return a string in the above format.
First of all, there is no YY, JJJ and DD formats as a custom date and time format. One solution might be to split your string Year and DayOfYear part and create a DateTime with JulianCalendar class.
string s = "05365";
int year = Convert.ToInt32(s.Substring(0, 2));
// Get year part from your string
int dayofyear = Convert.ToInt32(s.Substring(2));
// Get day of years part from your string
DateTime dt = new DateTime(1999 + year, 12, 18, new JulianCalendar());
// Initialize a new DateTime one day before year value.
// Added 1999 to year part because it makes 5 AD as a year if we don't.
// In our case, it is 2004/12/31
dt = dt.AddDays(dayofyear);
// Since we have a last day of one year before, we can add dayofyear to get exact date
I initialized this new DateTime(.. part with 18th December because
From Julian Calendar
Consequently, the Julian calendar is currently 13 days behind the
Gregorian calendar; for instance, 1 January in the Julian calendar is
14 January in the Gregorian.
And you can format your dt like;
dt.ToString("MMddyy", CultureInfo.InvariantCulture) //123105
I honestly didn't like this way but this is the only one I can imagine as a solution.

convert string in a foreign language to date

I have these input:
27 februari 2014
14 maart 2013
7 november 2013
I would like to convert them all to date field as below:
27-02-2014
14-03-2013
17-11-2013
I have tried this method: DateTime enteredDate = DateTime.Parse(s); but it does not work, the error message was:
The string was not recognized as a valid DateTime. There is a unknown
word starting at index 3.
This appears as Dutch, you can parse it by passing new CultureInfo("nl-NL") to DateTime.ParseExact like:
string str = "27 februari 2014";
DateTime dt = DateTime.ParseExact(str, "d MMMM yyyy",
new System.Globalization.CultureInfoCultureInfo("nl-NL"));
Use single d which would consider both single and double digit day part.
To get the formatted output use:
string formattedDate = dt.ToString("dd-MM-yyyy", System.Globalization.CultureInfoCultureInfo.InvariantCulture);
DateTime allows you to provide a CultureInfo, which may be enough for you. If not, and you only get one foreign language, you could simply replace the the words by the correct English ones.

Categories