Convert timestamp string to DateTime object in c# - c#

I have timestamp strings in the following format 5/1/2012 3:38:27 PM. How do I convert it to a DateTime object in c#

var date = DateTime.ParseExact("5/1/2012 3:38:27 PM",
"M/d/yyyy h:mm:ss tt",
CultureInfo.InvariantCulture);

You input string looks like in en-us format, which is M/d/yyyy h/mm/ss tt. You have to use proper CultureInfo instance while parsing:
var ci = System.Globalization.CultureInfo.GetCultureInfo("en-us");
var value = DateTime.Parse("5/1/2012 3:38:27 PM", ci);
or
var ci = new System.Globalization.CultureInfo("en-us");

Try to use DateTime.ParseExact method like;
string s = "5/1/2012 3:38:27 PM";
DateTime date = DateTime.ParseExact(s, "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
Console.WriteLine(date);
Converts the specified string representation of a date and time to its
DateTime equivalent using the specified format and culture-specific
format information. The format of the string representation must match
the specified format exactly.
Output will be;
01.05.2012 15:38:27
Be aware, this output can change based which Culture you used. Since my Culture is tr-TR, the date operator is . our culture.
Here is a DEMO.

Try the DateTime.ParseExact method

http://www.codeproject.com/Articles/14743/Easy-String-to-DateTime-DateTime-to-String-and-For
this maybe helps you. There you can find a detailled explanation of the ParseExact parameters.

Related

DateTime.ParseExact not working in C#, Date format Conversion not working

Parse Time not working as I want to convert "13-06-2019 00:00:00"(dd-MM-yyyy HH:mm:ss) to "06-13-2019 00:00:00"(MM-dd-yyyy HH:mm:ss)
tried with Convert.toDateTime() and DateTime.ParseExact()
IFormatProvider culture = new CultureInfo("en-US");
var a = DateTime.ParseExact(a, "MM-dd-yyyy hh:mm:ss", CultureInfo.InvariantCulture);
var b = DateTime.ParseExact(a, "yyyy-MM-dd HH:mm:ss", null);
var c = DateTime.ParseExact(a, "yyyy-MM-dd HH:mm:ss", culture);
Nothing working in it
DateTime structure uses Gregorian calendar under the hood and there is no 13th month in that calendar.
So, parsing 13 with MM specifier is wrong. I strongly suspect that you try to use dd-MM-yyyy HH:mm:ss format instead.
string a = "13-06-2019 00:00:00";
DateTime b = DateTime.ParseExact(a, "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
Here a demonstration
Your second and third examples also don't work since their formats are completely different than your string. When you parse your string with ParseExact method, your strings and your format should match exactly.
Also I want to mention that, both hh and HH specifiers would work in my code example. But as a general format consideration, using dd-MM-yyyy HH:mm:ss format is much more common and reliable than the other option.
The format parameter of DateTime.ParseExact(date,format,culture) is the source format of the date string to be converted and the return value is type date which you can convert back to string as per the desired format.
var a = "13-06-2019 00:00:00";
IFormatProvider culture = new CultureInfo("en-US");
DateTime b = DateTime.ParseExact(a, "dd-MM-yyyy hh:mm:ss", CultureInfo.InvariantCulture);
Console.WriteLine($"{b:MM-dd-yyyy HH:mm:ss}");

How get DateTime.Now with "AM" not "ق.ظ"

I try to get DateTime.Now , but what I get is:
'23/05/2016 03:16:51 ق.ظ'
I want to have
'23/05/2016 03:16:51 AM'
or something like this
Then you current culture seems to be an arabic one. You can use the overload of DateTime.ToString:
var enUsCulture = new CultureInfo("en-US");
string result = DateTime.Now.ToString( enUsCulture );
an an alternative you could pass the exact format with CultureInfo.InvariantCulture(to avoid that / will be replaced with your current culture's date separator):
string result = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
The InvariantCulture avoids that the "/" custom format specifier will cause / to be replaced with your current culture's date separator.
You could create a specific CultureInfo with your requirements starting from the CurrentCulture
CultureInfo ci = new CultureInfo(CultureInfo.CurrentCulture.LCID);
ci.DateTimeFormat.AMDesignator = "AM";
ci.DateTimeFormat.PMDesignator = "PM";
ci.DateTimeFormat.LongTimePattern = "HH:mm:ss tt";
string result = DateTime.Now.ToString(ci);
Console.WriteLine(result);
I think CultureInfo.InvariantCulture is the key here
DateTime now = DateTime.Now;
string result = now.ToString("dd MMM yyyy hh:mm tt", CultureInfo.InvariantCulture);
Console.WriteLine(result);
This should give you "23 May 2016 02:32 PM", you can further edit the date and time by using other setting in the string format specifier. But keep InvarianCulture and tt in order to recieve AP/PM.
For all possible formats and some examples check these links
https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
http://www.dotnetperls.com/datetime-format

Converting string to date time

I have a date which comes in a string like so:
09/25/2014 09:18:24
I need it like this (yyyy-mm-dd):
2014-09-25 09:18:24
The object that this date goes into is a nullable date.
Tried this does not work:
DateTime formattedDate;
bool result = DateTime.TryParseExact(modifiedDate, "yyyy-MM-dd",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out formattedDate);
Any clues?
Thanks in advance.
From DateTime.TryParseExact
Converts the specified string representation of a date and time to its
DateTime equivalent. The format of the string representation must
match a specified format exactly.
In your case, they are not. Use yyyy-MM-dd HH:mm:ss format instead.
string s = "2014-09-25 09:18:24";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy-MM-dd HH:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt);
}
It is a little bit unclear but if your string is 09/25/2014 09:18:24, then you can use MM/dd/yyyy HH:mm:ss format instead. Just a tip, "/" custom format specifier has a special meaning as replace me with current culture or supplied culture date separator. That means, if your CurrentCulture or supplied culture's DateSeparator is not /, your parsing operation will fail even if your format and string matches exactly.
If you have already a DateTime and you want to format it, you can use DateTime.ToString(string) method like;
dt.ToString("yyyy-mm-dd", CultureInfo.InvariantCulture); // 2014-09-25
or
dt.ToString("yyyy-mm-dd HH:mm:ss", CultureInfo.InvariantCulture); // 2014-09-25 09:18:24
Remember, a DateTime does not have any implicit format. It just contains date and time values. String representations of them have formats.
In answer to your question, to convert it as you prefer, do it like this:
string originalDate = "09/25/2014 09:18:24";
DateTime formattedDate;
if (DateTime.TryParseExact(originalDate, "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out formattedDate))
{
string output = formattedDate.ToString("yyyy-mm-dd HH:mm:ss", CultureInfo.InvariantCulture);
}
And then output will have your desired format.
DateTime dateOf = Convert.ToDateTime("09/25/2014 09:18:24");
string myFormat = "yyyy-mm-dd";
string myDate = dateOf.ToString(myFormat); // output 2014-18-25
Datetime format

How to find exact format of a date string?

I need to know exact date format that will perse the string 16-Aug-78 12:00:00 AM. I have tried various string like "ss-MMM-yy hh:mm:ss". Is there any way for finding it to converting to any general format. I am using CultureInfo.InvariantCulture class.
Your string format is wrong. It has to match your string format exactly. You can use dd-MMM-yy hh:mm:ss tt format instead.
Here an example in LINQPad.
string s = "16-Aug-78 12:00:00 AM";
var date = DateTime.ParseExact(s, "dd-MMM-yy hh:mm:ss tt",
CultureInfo.InvariantCulture);
date.Dump();
Custom Date and Time Format Strings
Or, since dd-MMM-yy hh:mm:ss tt is a standart date and time format for InvariantCulture, you can directly DateTime.Parse method like;
string s = "16-Aug-78 12:00:00 AM";
var date = DateTime.Parse(s, CultureInfo.InvariantCulture);
date.Dump();
Here a demonstration.
Is there any way for finding it to converting to any general format?
There is no way to get format of a string except you create your own formatting. Only you can know what is your string format exactly, computer can't.
For example; 01/02/2014 can be 1 February 2014 or 2 January 2014 depends on which custom format you can parse it.
Try as below
var dstring = "16-Aug-78 12:00:00 AM";
DateTime result;
var matchingCulture = CultureInfo.GetCultures(CultureTypes.AllCultures).FirstOrDefault(ci => DateTime.TryParse(dstring, ci, DateTimeStyles.None, out result))
You have wrong format string, you are using ss for day it should be dd. This article Custom Date and Time Format Strings explains what you need for custom format.
Use
"dd-MMM-yy hh:mm:ss tt"
Instead of
"ss-MMM-yy hh:mm:ss"
You can use DateTime.ParseExact to parse the string.
DateTime dt = DateTime.ParseExact("16-Aug-78 12:00:00 AM", "dd-MMM-yy hh:mm:ss tt", CultureInfo.InvariantCulture, DateTimeStyles.None);
You can try with DateTime.TryParseExact():
string strDate = "16-Aug-78 12:00:00 AM";
DateTime datDate;
if(DateTime.TryParseExact(strDate , new string[] {"dd-MMM-yy hh:mm:ss tt" },
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out datDate))
{
Console.WriteLine(datDate);
}
else
{
Console.WriteLine("Error in datetime format");
}

Display datetime into MM/dd/yyyy HH:mm format c#

In database datetime is being stored in MM-dd-yyyy HH:mm:ss fromat.
However, I want to display datetime in "MM/dd/yyyy HH:mm" format.
I tried it by using String.Format().
txtCampaignStartDate.Text = String.Format("{0:MM/dd/yyyy
HH:mm}",appCampaignModel.CampaignStartDateTime);
Here appCampaignModel.CampaignStartDateTime is DateTime object having value in "MM-dd-yyyy HH:mm" format.
I want to display in "MM/dd/yyyy HH:mm" format.
Can anyone help me for this?
The slashes in this format MM/dd/yyyy HH:mm mean: "replace me with the actual separator of the current culture". You have to use CultureInfo.InvariantCulture explicitely:
txtCampaignStartDate.Text = appCampaignModel.CampaignStartDateTime.ToString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
The "/" Custom Format Specifier
In database datetime is being stored in MM-dd-yyyy HH:mm:ss fromat.
Don't store datetimes with a format which means that you store them as (n)varchar. Use datetime instead.
txtCampaignStartDate.Text = appCampaignModel.CampaignStartDateTime
.ToString().Replace("-","/");
or
String.Format("{0:MM/dd/yyyy HH:mm}", dt);
Check : String Format for DateTime [C#]
or
String date = dt.ToString("MM/dd/yyyy HH:mm", DateTimeFormatInfo.InvariantInfo);
DateTime.ToString Method (String, IFormatProvider)
Why not just a simple replace?
txtCampaignStartDate.Text = BadString.Replace("-","/");
try using an added culture info:
CultureInfo ci = new CultureInfo("en-US");
txtCampaignStartDate.Text =
appCampaignModel.CampaignStartDateTime.ToString("MM/dd/yyyy HH:mm", ci);
p.s. the culture info used is an example.
To display your date in format you specified:
txtCampaignStartDate.Text = appCampaignModel.CampaignStartDateTime.ToString("g",DateTimeFormatInfo.InvariantInfo)
And for more date time formats you can go through this link.
Since you already have a DateTime object, just ToString it how you want:
appCampaignModel.CampaignStartDateTime.ToString("MM/dd/yyyy HH:mm");

Categories

Resources