how to convert date with 'T' to/from string in C# - c#

I used following functions to convert DateTime from/into string:
DATE_OBJ.ToString(DATE_FORMAT);
DateTime.ParseExact(Date_string, DATE_FORMAT, null);
Now I've got to work with follow format 2012-03-20T14:18:25.000+04:00
Which format should I use to convert it correctly to string and generate string like that from DateTime object?

You can go from DateTime to that format with
DateTime dt = new DateTime();
dt.ToString("o");
and from that format to DateTime with
DateTimeOffset.Parse(dateString);
Here is some more info on DateTime format:
http://www.dotnetperls.com/datetime-format

You are better of using DateTimeOffSet like:
string str = " 2012-03-20T14:18:25.000+04:00";
DateTimeOffset dto = DateTimeOffset.Parse(str);
//Get the date object from the string.
DateTime dtObject = dto.DateTime;
//Convert the DateTimeOffSet to string.
string newVal = dto.ToString("o");

You cannot do this from DateTime, as DateTime holds no TimeZone info.
This is close: string.Format("{0:s}", dt) will give 2012-03-20T14:18:25.
See: http://www.csharp-examples.net/string-format-datetime/
You could extend this to: string.Format("{0:s}.{0:fff}", dt), which will give 2012-03-20T14:18:25.000
But you better have a look at DateTimeOffset: DateTime vs DateTimeOffset
(Not advisable, but to fake it and still use DateTime: string.Format("{0:s}.{0:fff}+04:00", dt))

If that is a string you receive then you can split the string by T and use only the first part which is the Date component of the whole string and parse that.
ex:
string dateTimeAsString = "2012-03-20T14:18:25.000+04:00";
string dateComponent = dateTimeAsString.Splic('T')[0];
DateTime date = DateTime.ParseExact(dateComponent, "yyyy-MM-dd",null);

Related

Format DateTime object from System time format to required format

My system time is of the format dd-MMM-yy (02-Dec-16). The format I want to convert it to is "yyyy/MM/dd". I've basically been playing around with all the other datetime formats that my system offers and this is the parsing statement I've figured out that works for All of them (except this) -
CultureInfo provider = CultureInfo.InvariantCulture;
string date_format = "yyyy/MM/dd HH:mm:ss tt";
DateTime now_value = DateTime.ParseExact(DateTime.Now.ToString(date_format), date_format, provider);
return now_value.ToString(date_format);
But this doesn't work for the aforementioned dd-MMM-yy format. Can someone please tell me what I am doing wrong here?
(Sidebar -Is there a more efficient way in which I can write this above snippet?)
You don't need to convert DateTime to string and then convert back to DateTime and again back to string, if you have DateTime input just call the ToString with the format as below
string dt =DateTime.Now.ToString("yyyy/MMM/dd", CultureInfo.InvariantCulture);
for your example :
DateTime now_value = DateTime.ParseExact("02-Dec-16", "dd-MMM-yy", System.Globalization.CultureInfo.InvariantCulture);
return now_value.ToString("yyyy/MM/dd");
Try This:
string date_format = "yyyy-MMM-dd";
string date_now = DateTime.Now.ToString(date_format,CultureInfo.CreateSpecificCulture("en-US"));
return date_now;
Even This should also work:
string date_format = "yyyy-MMM-dd";
string date_now = DateTime.Now.ToString(date_format);
return date_now;
I think best way would be to create an extension method for multiple date formats,
var inputDate = "02-Dec-2016";
string[] availaible_input_date_format = { "dd-MMM-yyyy", "dd/MMM/yyyy" }; // add as many formats availible
var date_format = "yyyy/MMM/dd";
DateTime outputDate;
DateTime.TryParseExact(inputDate, availaible_input_date_format, null, DateTimeStyles.None, out outputDate);
Console.WriteLine(outputDate.ToString(date_format));
You can try this:
datetime yourdatetime = new datetime();
string converteddatetime = yourdatetime.toString("yyyy/MM/dd");

Remove time from time and date

I have a variable openDate which holds date and time, and I would like to strip just the date. I tried the below example and it is not working. What am I doing wrong, or rather how should I do it because the variable openDate remains the same even after trying to strip just the date? The value of openDate is "2012-03-08 00:00:00"
openDate = ! string.IsNullOrEmpty(node.ChildNodes[f].Attributes["ows_PMO_x0020_Origination_x0020_Date"].Value)
? node.ChildNodes[f].Attributes["ows_PMO_x0020_Origination_x0020_Date"].Value
: "" ;
openDate = String.Format("{0:MM/dd/yyyy}", openDate);
considering openDate is of a String type, i would do this
var dt = DateTime.Parse(openDate).ToString("MM/dd/yyyy");
From your code it is clear that openDate is of type string and you have value that is a string representation of DateTime, you can apply DateTime formatting on string values.
You have multiple options.
Convert string openDate to a DateTime value and then apply formatting
Do some string operations to extract the date part from your string value.
String operations:
string openDate = "2012-03-08 00:00:00";
string formatted = openDate.Substring(0, openDate.IndexOf(' '));
DateTime Parsing.
DateTime parsedDateTime = DateTime.Parse(openDate);
string formattedDateTime = parsedDateTime.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);
You need to convert your date into a DateTime object first. See examples here if your string is in a different or custom format.
openDate = !string.IsNullOrEmpty(node.ChildNodes[f].Attributes["ows_PMO_x0020_Origination_x0020_Date"].Value)? node.ChildNodes[f].Attributes["ows_PMO_x0020_Origination_x0020_Date"].Value: "" ;
//openDate is a string at this point. You'll need to convert it to a datetime object first, for the following line to work:
var dtObject = DateTime.Parse(openDate);
//Format the newly created datetime object
openDate = String.Format("{0:MM/dd/yyyy}", dtObject);
You can format datetime using:
If it is a datetime:
OpenDate = OpenDate.ToString("yyyy-mm-dd");
If the datatype is not datetime and you are sure the format will always be that then you can always convcert the string to datetime and use the method described above.
Convert.ToDateTime(openDate).ToString("yyyy-mm-dd");
The answers are great, especially if you would like to control the format of your 'time' part. Here is teh simplest way to get what you are after:
var dt = Convert.ToDateTime("2012-03-08 00:00:04");
Console.WriteLine(dt.ToLongTimeString());
Console.WriteLine(dt.TimeOfDay);
Output:
Use the following - openDate = openDate.Date

DateTime.Parse Not Parsing

I'm trying to return the date as "2015-06-18"
string strDate = DateTime.Now.ToString("yyyy-MM-dd");
DateTime newDate = DateTime.Parse(strDate);
This returns "2015/06/18 hh:mm:ss"
What am I missing?
If you want a particular output format, you can specify one yourself.
string strDate = DateTime.Now.ToString("yyyy-MM-dd");
DateTime newDate = DateTime.Parse(strDate);
string output = newDate.ToString("yyyy-MM-dd");
Console.WriteLine (output); // produces 2015-06-18 right now
The DateTime structure in .net always includes the time of day, and there is no built-in way to store only a date, so if you want to exclude it, you'll need to use the formatting options.
What you need is to format the datetime object.
newDate.ToString("yyyy-MM-dd") -> 2015-06-19
Why don't you just use the DateTime.Date property?
DateTime date1 = DateTime.Now;
Console.WriteLine(date1.ToString());
// Get date-only portion of date, without its time.
DateTime dateOnly = date1.Date;
// Display date using short date string.
Console.WriteLine(dateOnly.ToString("yyyy-MM-dd"));

C# with mongodb DateTime Convert

I want to convert "ISODate(\"2014-11-13T18:43:33.868Z\")" to c# datetime ex 2014-11-13 18:43:33.
Value "ISODate(\"2014-11-13T18:43:33.868Z\")" take from MongoDB collection.
Please Help.
You can set DateTime in C# to UTC
var createDate = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc)
or
dateTime = DateTime.SpecifyKind(dateTime, DateTimeKind.Utc)
Then insert type DateTime into mongodb
It worked in my case.
You can store your date as a BsonDateTime object when you pull it from the database, then convert it as follows:
DateTime dt = bdt.ToUniversalTime();
And you may find this question useful to learn more about how ToUniversalTime() works.
If I understand clearly, just because it writes ISODate in your string, that doesn't make it ISO 8601 format. The "O" or "o" standard format specifier complies ISO 8601 format and which is "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" custom format string for a DateTime. That doesn't match with your string format.
If your all strings has a stable format like this, you can use custom date and time formats with literal string delimiter like;
string s = "ISODate(\"2014-11-13T18:43:33.868Z\")";
string format = "'ISODate(\"'yyyy-MM-dd'T'HH:mm:ss.fff'Z\")'";
DateTime date;
if(DateTime.TryParseExact(s, format, CultureInfo.InvariantCulture,
DateTimeStyles.None, out date))
{
Console.WriteLine (date);
}
If you want to string representation of your DateTime with "2014-11-13 18:43:33" format, you can use DateTime.ToString() method like;
date.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);

Convert a string to datetime format in asp .net

I have a date time string "12-24-2013 15:19:29" which is in "MM-dd-yyyy HH:mm:ss". I want to convert this string to datetime. But the format should not change.ie, it should be the same "MM-dd-yyyy HH:mm:ss" format.
When I used following method,
DateTime dt2 = DateTime.ParseExact(date31strin, "MM-dd-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
the format is changed to "dd-MM-yyyy HH:mm:ss". I have tried some other method also, but still getting this same format.
First, you should be parsing the string to a DateTime and then format it to the second format using ToString() method.
//Convert your string to a DateTime
DateTime dt2 = DateTime.ParseExact(date31strin,
"MM-dd-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
//If you want to change the format
string secondFormat = dt2.ToString("Second format string");
Note: Date is a Date and it does not have a format. If you need to convert the string to a DateTime, first line of code is enough
You are not changing the format.
You are parsing a string into a DateTime object which does not have a format.
When you decide to present the DateTime, you can format it any way you wish.
to parse String to DateTime use method DateTime.TryParse (http://msdn.microsoft.com/cs-cz/library/ch92fbc1%28v=vs.110%29.aspx) and then use DateTime formating (http://msdn.microsoft.com/en-us/library/az4se3k1%28v=vs.110%29.aspx) to output to aspx page
//frndzz if you are using j query and you don't convert date in(MM/dd/yyyy) to //(dd/MM/yyyy) then this code will help you
// i try it and i get the answer
string sd=txtmydate.Text //sd=04/27/2015 (MM-dd-yyyy) format
string [] sdate = sd.Split('-');
string fd = sdate[1];
fd=string.Concat(sdate[1],"-",sdate[0],"-",sdate[2]);
DateTime dt = Convert.ToDateTime(fd);
txtshow.Text = dt.ToString("dd/MM/yyyy");
//txtshow will show you date as 27-04-2015 (dd/MM/yyyy) format
thanks
How to convert string to DateTime:
string iDate = "Absent";
aEmployeeAttendence.Intime = DateTime.Parse(iDate);
//aEmployeeAttendence (object)
//Intime (field)

Categories