Convert Full Date and Day - c#

I am wondering if it possible to convert a Full Date and Day e.g.
Thursday 18th of April 2013
to a string (DD/MM/YYYY)

Yes check into Standard Date Time Format strings, and Custom Date Time Format strings

You can try using the DateTime.Parse(string str) method.
For example,
DateTime.Parse("Thu, 18 April 2013");
gives the following output,
04/18/2013 00:00:00

There may be an easier way, but here is a quick method that came to mind based upon my understanding of your question. There is a bit of extra code, so that you can add into a blank Windows form project and see the value.
String strEntry = #"Thursday 18th of April 2013";
DateTime dteValue = DateTime.MinValue;
strEntry = strEntry.Replace("of", null);
strEntry = strEntry.Replace("rd ", " ");
strEntry = strEntry.Replace("th", null);
strEntry = strEntry.Replace("st", null);
DateTime.TryParse(strEntry, out dteValue);
String strFormat = dteValue.ToString("dd/MM/yyyy");
MessageBox.Show(strFormat, "Date Value", MessageBoxButtons.OK);

Related

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.

How to get the day (Mon, tue, etc... Not a number) of the computer's clock?

I want to get the day of my computer, but in a word instead of a number. How do I do this?
Use:
string day = DateTime.Now.DayOfWeek.ToString();
Here is the MSDN Reference.
DateTime dt = DateTime.Now;
Console.WriteLine("The day of the week for {0:d} is {1}.", dt, dt.DayOfWeek);
Use custom date and time format strings
custom date and time format strings
string dayOfWeek = DateTime.Now.ToString("ddd");
Console.WriteLine(dayOfWeek);
This will print out "Mon, Tue" etc

Convert string to Time

I have a time that is 16:23:01. I tried using DateTime.ParseExact, but it's not working.
Here is my code:
string Time = "16:23:01";
DateTime date = DateTime.ParseExact(Time, "hh:mm:ss tt", System.Globalization.CultureInfo.CurrentCulture);
lblClock.Text = date.ToString();
I want it to show in the label as 04:23:01 PM.
"16:23:01" doesn't match the pattern of "hh:mm:ss tt" - it doesn't have an am/pm designator, and 16 clearly isn't in a 12-hour clock. You're specifying that format in the parsing part, so you need to match the format of the existing data. You want:
DateTime dateTime = DateTime.ParseExact(time, "HH:mm:ss",
CultureInfo.InvariantCulture);
(Note the invariant culture, not the current culture - assuming your input genuinely always uses colons.)
If you want to format it to hh:mm:ss tt, then you need to put that part in the ToString call:
lblClock.Text = date.ToString("hh:mm:ss tt", CultureInfo.CurrentCulture);
Or better yet (IMO) use "whatever the long time pattern is for the culture":
lblClock.Text = date.ToString("T", CultureInfo.CurrentCulture);
Also note that hh is unusual; typically you don't want to 0-left-pad the number for numbers less than 10.
(Also consider using my Noda Time API, which has a LocalTime type - a more appropriate match for just a "time of day".)
string Time = "16:23:01";
DateTime date = DateTime.Parse(Time, System.Globalization.CultureInfo.CurrentCulture);
string t = date.ToString("HH:mm:ss tt");
This gives you the needed results:
string time = "16:23:01";
var result = Convert.ToDateTime(time);
string test = result.ToString("hh:mm:ss tt", CultureInfo.CurrentCulture);
//This gives you "04:23:01 PM" string
You could also use CultureInfo.CreateSpecificCulture("en-US") as not all cultures will display AM/PM.
The accepted solution doesn't cover edge cases.
I found the way to do this with 4KB script. Handle your input and convert a data.
Examples:
00:00:00 -> 00:00:00
12:01 -> 12:01:00
12 -> 12:00:00
25 -> 00:00:00
12:60:60 -> 12:00:00
1dg46 -> 14:06
You got the idea...
Check it https://github.com/alekspetrov/time-input-js

Remove leading zero form month 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();

DateTime.TryParseExact CultureInfo.InvariantCulture

Can anyone see what I'm doing wrong, I'm trying to parse the date to ensure its a valid date, if so convert it to the format I require.
I have tried different ways of doing this, but all return 01/01/0001 00:00:00.
value of string parseArrivalDate = 02/02/2013
DateTime ukDateFormat;
string ukFormat = "0:ddd, MMM d, yyyy";
DateTime.TryParseExact(parseArrivalDate, ukFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out ukDateFormat);
DateTime test = ukDateFormat;
-------------------------------------EDIT-------------------------------
OK sorry, I did not explain it very well. If I enter UK format say 27/02/2013, and when I had UK format as dd/MM/yyyy it worked ok, problem was when I was entering US or any other format, it was returning the incorrect date, so I was changing the format round thinking that was the problem.
It has now dawned on me after reading your comments, that I had the uk format correct 1st time, so my problem is, how can I change the code, so that any date format can be parsed correctly.
Hope that makes more sense
Thanks
Your string
"0:ddd, MMM d, yyyy"
has a number 0, a colon :, and a format corresponding to
"Wed, Mar 27, 2013"
for example, if the culture is "en-GB" ("English (United Kingdom)"). It probably comes from a String.Format, Console.WriteLine or similar method call, where it is put into braces {} to format a text, as in
Console.WriteLine("The date {0:ddd, MMM d, yyyy} was selected.", someDateTime);
It would work with code like:
string arrivalDateString = "Wed, Mar 27, 2013";
...
DateTime result;
string yourFormat = "ddd, MMM d, yyyy"; // no "0:" part
bool isOK = DateTime.TryParseExact(arrivalDateString, yourFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out result);
if (isOK)
{
// Worked! Answer is in 'result' variable
}
else
{
// Didn't work! 'result' variable holds midnight 1 January 0001
}
The format that corresponds to "27/03/2013" is "dd/MM/yyyy" (or "d/M/yyyy"). The format that corresponds to "03/27/2013" is "MM/dd/yyyy" (or "M/d/yyyy").
It is not possible to have one method that handles both styles of dates, since a string like
"01/04/2013" /* ambiguous */
could mean either
1 April 2013
January 4, 2013
so it's ambiguous, and there's no way we can tell what date is meant. See also Wikipedia: Calendar date → Date format.
your date string is: 02/02/2013 and the format you are using is "0:ddd, MMM d, yyyy" which is wrong, it should be MM/dd/yyyy if its month first.
DateTime ukDateFormat;
string ukFormat = "MM/dd/yyyy";
DateTime.TryParseExact(parseArrivalDate, ukFormat,CultureInfo.InvariantCulture,DateTimeStyles.None, out ukDateFormat);
DateTime test = ukDateFormat;
If the date you have specified contains day first then month, then use the format "dd/MM/yyyy", By the way you can using single d and M for both single digit and double digits day/month.
Currently you are getting the DateTime.MinValue, since parsing is failing because of the invalid format.
I have no idea what you expect, but your input string does not met your ukFormat pattern! So it's totally right behavior.
Change your pattern to ""dd/MM/yyyy"" to make TryParseExact work.
Your provided format looks a little strange. Try to replace it with this
string ukFormat = "dd/MM/yyyy";
And read the documentation on this.
Thanks everyone for helping me understand where I was going wrong, the code below is what I have came up with although not perfect as 03/06/2013 UK is different than the meaning of 03/06/2013 US.
I have added text above the text box asking people to use format dd/mm/yyyy.
string getArrivalDate = ArrivalDate;
string getDepartureDate = DepartureDate;
string dteFormat = "dd/MM/yyyy";
DateTime result;
string arrivalDateParse;
string departureDateParse;
bool arrival = DateTime.TryParseExact(getArrivalDate, dteFormat, new CultureInfo("en-GB"), DateTimeStyles.None, out result);
if (arrival)
{
arrivalDateParse = getArrivalDate;
}
else
{
arrivalDateParse = "notvalid";
}
bool depart = DateTime.TryParseExact(getDepartureDate, dteFormat, new CultureInfo("en-GB"), DateTimeStyles.None, out result);
if (depart)
{
departureDateParse = getDepartureDate;
}
else
{
departureDateParse = "notvalid";
}
if (arrivalDateParse == "notvalid" || departureDateParse == "notvalid")
{
if (Request.IsAjaxRequest())
{
return Json(new { Confirm = "Date not in correct format" }, JsonRequestBehavior.AllowGet);
}
else
{
TempData["Error"] = "Sorry your arrival date or departure date is not a valid format, please enter date as dd/mm/yyyy example 02/12/2013";
return View("~/Views/Shared/Error.cshtml");
}
If anyone can improve on the code, it would be appreciated.
Thanks
George
Rather than using InvariantCulture for this consider using RoundTrip style (ISO-8601). See this MSDN article: http://msdn.microsoft.com/en-us/library/bb882584.aspx

Categories