String which is not in datetime format to DateTime - c#

I have a string which is not in a datetime format eg:20160503. How can i change it to Datetime. I tried using Substring. It is working.Is there any more efficient way? Below is what I have right now.
string a = "20160503";
int b = Convert.ToInt32(a.Substring(0, 4));
int c = Convert.ToInt32(a.Substring(4, 2));
int d = Convert.ToInt32(a.Substring(6, 2));
string date = b + "/" + c + "/" + d;
DateTime result = new DateTime();
DateTime.TryParse(date, out result);

Since you know the exact format of your datetime, you could try to use the ParseExact DateTime's method.
var dt = DateTime.ParseExact(a,"yyyyMMdd",CultureInfo.InvariantCulture);
For further info, please have a look here.

Try somthing like this:
Define your own parse format string to use.
string formatString = "yyyyMMdd";
string sample = "20160503";
DateTime dt = DateTime.ParseExact(sample,formatString,null);

Thanks for your replies. Finaly I ended up using DateTime.TryParseExact
string dateString = "20150503";
DateTime dateValue = new DateTime();
DateTime.TryParseExact(dateString, "yyyyMMdd", new CultureInfo("en-US"), DateTimeStyles.None, out dateValue);

Related

Combine date and time from string and convert to datetime

I have 2 strings (date(13/04/2021),time("06:30")) and I want to combine them together to datetime format and I am getting the below error.
System.FormatException: 'String was not recognized as a valid DateTime.'
What I am doing wrong?
if I change the tempdate format to "yyyy-dd-MM" I get the error there
var type = form["GymType"];
var time = form["states_ddl"];
var date = form["date2"];
var username = form["username"];
var numberofpersons = 0;
if (type == "2")
{
//gym
numberofpersons = 9;
}
else
{
//cross
numberofpersons = 5;
}
Booking toadd = new Booking();
var currenduser = User.Identity.GetUserId();
var tempdate = DateTime.ParseExact(date , "dd/MM/yyyy", CultureInfo.InvariantCulture);
DateTime d = DateTime.ParseExact(tempdate + " " + time, "yyyy-dd-MM HH:mm", CultureInfo.InvariantCulture);
What you do is convert de string to a dateTime 'tempdate', and than on the next line you convert it back to a string.
What i would do is convert the date as you do and parse the time separate, than add them together.
var tempdate = DateTime.ParseExact(date , "dd/MM/yyyy", CultureInfo.InvariantCulture);
var timspan = TimeSpan.Parse(time);
DateTime d = tempdate.Add(timspan);
You can use Convert to do this
var date = Convert.ToDateTime("13/04/2021 06:30");
try this
string d = "13/04/2021";
string t = "10:30PM";
string dateAndTime = d.Trim() + ' ' + t.Trim();
DateTime dt = DateTime.ParseExact(dateAndTime, "MM/dd/yyyy hh:mmtt",
CultureInfo.InvariantCulture, DateTimeStyles.None);
dt = DateTime.Parse(dateAndTime, CultureInfo.InvariantCulture,
DateTimeStyles.None);

C# ASP.NET: can't convert datetime to string

I want to convert a datetime to string.
But result now is returned as 04 August, 0016 which is not what I need.
I want result to be 04 August, 2016.
C# code:
DataTable dtGroupCurr = new DataTable();
dtGroupCurr = sourceGroupCurr.Tables[0];
var groupedCurr = (from dt2 in dtGroupCurr.AsEnumerable()
select new
{
S_DATE = dt2.Field<DateTime>("S_DATE"),
BANK_CODE = dt2.Field<string>("BANK_CODE"),
BANK_NAME = dt2.Field<string>("BANK_NAME")
}).Distinct().OrderBy(x => x.S_DATE);
foreach (var s in groupedCurr)
{
string rDate = s.S_DATE.ToString("yyyy/MM/dd");
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime date = DateTime.Parse(rDate, culture);
string sDate = date.ToString("dd MMMM, yyyy", CultureInfo.InvariantCulture);
}
Thanks in advance ;)
Try:
string sDate = s.S_DATE.ToString("dd MMMM, yyyy", new CultureInfo("en-US", true));
Or
string rDate = s.S_DATE.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture); // To avoid override
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime date = DateTime.Parse(rDate, culture);
string sDate = date.ToString("dd MMMM, yyyy", CultureInfo.InvariantCulture);
The "/" custom format specifier represents the date separator, which
is used to differentiate years, months, and days. The appropriate
localized date separator is retrieved from the
DateTimeFormatInfo.DateSeparator property of the current or specified
culture.
MSDN
Use the DateTime.ParseExact method and specify the format like below:
string rDate = s.S_DATE.ToString("yyyy/MM/dd");
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime date = DateTime.ParseExact(rDate, "yyyy/MM/dd", culture);
string sDate = date.ToString("dd MMMM, yyyy", CultureInfo.InvariantCulture);
Use Date or DateTime.ToShortDateString();
Or
Date.ToString("dd-MM-yyyy");

Separate Date and time with " (String.Format)

Is it possible to separate Date and time with ".
So it would be:
"ddMMyyyy","HHmmss"
Right now i have:
DateTime dt = aPacket.dtTimestamp;
string d = dt.ToString("\"ddMMyyyy\",\"HHmmss\"");
and String.Format shows me just "ddMMyyyy,HHmmss"
Thank you everyone for helping me !!! But i will mark the first answer as the right one
You can try formatting:
DateTime dt = DateTime.Now;
// "01072016","101511"
string d = String.Format("\"{0:ddMMyyyy}\",\"{0:HHmmss}\"", dt);
" is a formatting character, so it needs to be escaped with \, e.g.
string d = dt.ToString("\\\"ddMMyyyy\\\",\\\"HHmmss\\\"");
You may find a verbatim string slightly more readable:
string d = dt.ToString(#"\""ddMMyyyy\"",\""HHmmss\""");
Custom Date and Time Format Strings (MSDN)
I would say like this:
var now = DateTime.Now;
var date = now.ToString("ddMMyyyy", CultureInfo.InvariantCulture);
var time = now.ToString("HHmmss", CultureInfo.InvariantCulture);
var dt = string.Format(CultureInfo.InvariantCulture, "\"{0}\",\"{1}\"", date, time);
Console.WriteLine(dt);
You can try this:
var now = DateTime.Now;
var formattedDateTime = $"{now.ToString("ddMMyyyy")},{now.ToString("HHmmss")}";

Convert string dd/mm/yy to datetime

I need to convert a string format dd/mm/yy to a datetime.
I tried with:
DateTime d;
if (DateTime.TryParseExact(dateStr.Trim(), "dd/MM/yyyy", new CultureInfo("es-es"), DateTimeStyles.AssumeLocal, out d))
return d;
Your code seems ok, but also you can convert a string into datetime like below
DateTime d = DateTime.ParseExact("11/02/2016", "dd/MM/yyyy", CultureInfo.InvariantCulture);
return d;
if you have string as dd/MM/yy format and need to convert it as dd/MM/yyyy fomat datetime then you can do like this
DateTime temp = DateTime.ParseExact("11/02/16", "dd/MM/yy", CultureInfo.InvariantCulture);
DateTime d = DateTime.ParseExact(temp.ToString("dd/MM/yyyy"), "dd/MM/yyyy", CultureInfo.InvariantCulture);
return d
string dateBirth = ddlDay.SelectedItem.ToString() + "/" + ddlMonth.SelectedItem.ToString() + "/" + ddlYear.SelectedItem.ToString();
DateTime dt = DateTime.ParseExact(dateBirth, "dd/MM/yyyy", null);

take time and append to date to make datetime?

Say I have the following:
string fromTime = "8:00am";
string someDate = "06/01/2012";
I want to end up doing this:
DateTime dt = Convert.ToDateTime(someDate + someTime);
Basically I want to take a date and add the time to it with the result for the above to be
06/01/2012 8:00am
But have it stored in a datetime variable. Is this possible?
You could use the DateTime.TryParseExact method which allows you to specify a format when parsing:
class Program
{
static void Main()
{
string s = "06/01/2012 8:00am";
string format = "dd/MM/yyyy h:mmtt";
DateTime date;
if (DateTime.TryParseExact(s, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
Console.WriteLine(date);
}
}
}
Try this:
DateTime dt = DateTime.ParseExact(someDate + " " + someTime, "MM/dd/yyyy h:mmtt", CultureInfo.InvariantCulture);

Categories

Resources