How to format the datetime in c#? - datetime

I got the current datetime by using the following code.
DateTime dt = DateTime.Now;
But it is in the format of, 2015-02-23 17:25:07.123
how to convert this to the format of, "02/23/2015"?

"But it is in the format of"
No it isn't. It's just a DateTime. If you want a particular text representation, call ToString on it, specifying the format. For example:
DateTime now = DateTime.Now;
string formatted = now.ToString("MM/dd/yyyy");
You might also want to specify the culture to use for formatting - that way you could just say "Use the right short date format" for example.
See the MSDN pages on custom date/time format strings and standard date/time format strings for more details.

Try this,
String.Format("{0:MM/dd/yyyy}", dt);

Related

Format Date via Parameter

I have a DateTime variable (default formatting), and I would like to format it to a format to I receive from a string parameter.
I normally do something similar to: {myDate:yyyy-MM-dd}, and it works properly.
Now I have a lot of possible date formats and need to format according to the chosen one.
I have tried the following but returned garbage (ae0aor0aa):
string testFormat = "yyyy. MM. dd.";
{myDate:testFormat }
I have also tried to convert the date to string and back to date with ParseExact, but gave me an invalid date exception. NB: the date in myDate is valid, as I have checked it with the debugger.
Can you kindly advise?
Thanks to apc, it was easily solved by myDate.ToString(testFormat)

ASP.Net VB string to date based on format used in string

I'm using a JavaScript datepicker that gives me the selected date based on the language. So when the language is Dutch I get an output like 21-09-2017 (dd-mm-yyyy) And for English 21/09/2017.
When I want to cast these Strings to Dates (CDate) I get a problem with the format. Day = Month or Month = Day. What is the best way to make a Date from a string based on the format used in the string?
A solution would be to write a function for each specific culture to handle the dates but i'm guessing there is a default function in .Net??
You can use DateTime.ParseExact to get what you want as shown here.
You can provide the format like so:
dateString = "15/06/2008 08:30" //Your Date time
format = "g" //General Fromat
provider = New CultureInfo("fr-FR") //French
result = Date.ParseExact(dateString, format, provider) //Parsed Result
this will result in: 6/15/2008 8:30:00 AM
This or course only works if you know the culture. Also you may want to check out the Date Time Format Strings found here.
Convert.ToDateTime(String).ToString("dd-MM-yyyy")
OR
DateTime.ParseExact(String, "dd/MM/yyyy", CultureInfo.InvariantCulture)

ColdFusion - DateTime Format with GMT offset

I am using ColdFusion 10 to make some REST calls and the date returned is using a GMT offset.
Example: 2013-03-25T14:30:40-04:00
I need this formatted for 2 purposes:
Screen Display so it looks something like mm/dd/yyyy hh:mm:ss
To Insert into mySQL.
I have tried a variety of the CF time/date functions but continue to get the "is not a valid date format"
I thought maybe the #ParseDateTime(i.submitted_at,"pop")# would handle it with POP but same issue.
Spent a few hours now trying multiple variations and googling around now just going in circles. Any ideas would be greatly appreciated.
Thanks!
Have a look at the UDF DateConvertISO8601() on CFLib.
DateConvertISO8601(ISO8601dateString, targetZoneOffset) on CFLib
Description:
This function take a string that holds a date in ISO 8601 and converts it to ODBC datetime, but could be adapted to convert to whatever you like. It also will convert to a datetime in a timezone of your choice by specifying the offset, i.e. it could take a datetime in GMT and convert to PT. See http://www.w3.org/TR/NOTE-datetime for description of ISO 8601, the International Standard for the representation of dates and times.
Return Values:
Returns a datetime.
The source code is viewable at the link I provided.
This, 2013-03-25T14:30:40-04:00, is a string. If you run this:
x = left(2013-03-25T14:30:40-04:00, 19);
you get 2013-03-25T14:30:40. You can use the replace function to replace the T with a space. You can then to this
DateTimeVar =parsedatetime('2013-03-25 14:30:40');
Now you have a datetime variable that you can format. If necessary you can do a datediff with the offset from GMT.
This is an informational answer, not a direct answer to the question.
ColdFusion 11 has updated the ParseDateTime() function so that it will correctly convert the ISO-8601 date/time strings to a ColdFusion datetime object.
With a number of remote requests and responses, the date / time values can often be returned in ISO format. In your case, the mask looks like this:
YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)
In this ISO format, the T string is a literal representation of a marker where the time stamp starts in the string (with the offset following directly).
Below is a reusable function that will convert an ISO date format into a useable ColdFusion date time object:
<cffunction name="ISOToDateTime" access="public" returntype="string" output="false"
hint="Converts an ISO 8601 date/time stamp with optional dashes to a ColdFusion
date/time stamp.">
<cfargument name="Date" type="string" required="true" hint="ISO 8601 date/time stamp." />
<cfreturn ARGUMENTS.Date.ReplaceFirst(
"^.*?(\d{4})-?(\d{2})-?(\d{2})T([\d:]+).*$",
"$1-$2-$3 $4"
) />
</cffunction>
You can then call the function like so to output or return a ColdFusion-friendly version of the date time:
ISOToDateTime( "2013-03-25T14:30:40-04:00" )
That function is courtesy of Ben Nadel. The original blog post can be found here:
http://www.bennadel.com/blog/811-Converting-ISO-Date-Time-To-ColdFusion-Date-Time.htm
You can also convert the date time value using the offset, if required. Again, Ben Nadel has a great blog post outlining how to accomplish this:
http://www.bennadel.com/blog/1595-Converting-To-GMT-And-From-GMT-In-ColdFusion-For-Use-With-HTTP-Time-Stamps.htm
CF10 can use this code as stated in the example of the parseDateTime() doc.
<cfset string = "1997-07-16T19:20:30+01:00">
<cfset date = parseDateTime(string, "yyyy-MM-dd'T'HH:mm:ssX")>

DateTime format conversion to string ignores AM/PM

I am trying to convert DateTime object to string using formatting but due to some strange reason, it ignores AM/PM. It would just take the magnitude of the Hour in the object.
I am using the following format:
StartDate.ToString("yyyy-MM-dd hh:mm:ss.fff");
and
String.Format("0:yyyy-MM-dd hh:mm:ss.fff", StartDate);
I don't think that there is a difference between the two, but just wanted to give it a try. If I pass a value 4/28/2012 6:00:00 AM or 4/28/2012 6:00:00 PM, the result is the same "2012-04-27 06:00:00.000"
You've used hh which uses the 12-hour clock. You want HH which uses the 24-hour clock.
See MSDN for more details about custom format strings.
Note that you may wish to specify the invariant culture, unless you really want the time separator to depend on the current culture:
string formatted = StartDate.ToString("yyyy-MM-dd HH:mm:ss.fff",
CultureInfo.InvariantCulture);
(Note that you shouldn't have the braces if you're passing the format string to ToString. I'll assume this was just a typo in the question.)
If you want to use the 12-hour clock, use tt in the format string to produce the AM/PM designator.

How to convert date to mm/dd/yyyy format

I want to convert dateformat to mm/dd/yyyy. Whatever dateformat is coming in textbox, I want to convert it into mm/dd/yyyy.
First you need to get it into a datetime object. The most common standards work via:
DateTime x = DateTime.Parse(txtDate.Text);
If you expect a freaky format, you still have to know what format it is:
DateTime x;
DateTime.TryParseExact(txtDate.Text, "YYddd", out x);
Then simply output the data:
string date = x.ToString("MM/dd/yyyy");
But you really need to enforce your formatting using regex, validators, scout's honor - something.
see MSDN for full details.
You will need to parse the input to a DateTime object and then convert it to any text format you want.
If you are unsure what format you may be getting, maybe it is a good idea to restrict the user to a single format (using validation or better yet a date picker).

Resources