Converting a String to DateTime with new format - c#

How do you convert a string such as 13.11.2017 into a DateTime with that format 13/11/2017
I tried several ways but i didn't get solution .
string Arrival = Request.QueryString["Arrival"];//13.11.2017
DateTime datee = DateTime.ParseExact(Arrival , "dd/MM/yyyy", null);
here is updated code i split the string :
string Arrival = Request.QueryString["Arrival"];//13.11.2017
string year = Arrival.Split('.')[2];
string month = Arrival.Split('.')[1];
string day = Arrival.Split('.')[0];
string date = day + "/" + month + "/" + year;
DateTime datee = DateTime.ParseExact(date, "dd/MM/yyyy", null);

Observe:
// the input string
string inputString = "13.11.2017";
// parse the input string with a specific format to create a DateTime
DateTime dt = DateTime.ParseExact(inputString, "dd.MM.yyyy", CultureInfo.InvariantCulture);
// create a string from the DateTime using a different specific format
string outputString = dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
// output the string
Console.WriteLine(outputString); // "13/11/2017"
Note that a DateTime itself does not have any particular format. A format only comes into play when going to or from a string.
Also note that by using the invariant culture here, we are avoiding any issues that may arise if the current culture was one that used different date separators or a different calendar system.

using System.Text.RegularExpressions;
string Arrival = Request.QueryString["Arrival"]; // 13.11.2017
string dateString = Regex.Replace(Arrival, #"\.", "/"); // 13/11/2017
DateTime date = DateTime.ParseExact(dateString , "dd/MM/yyyy", null); // 11/13/2017 00:00:00

Had the same problem with Russian locale.
Currently using ISO format everywhere to avoid incorrect DateTime understandings (like MM.dd when you mean dd.MM).
public static string ToIsoStr(this DateTime dateTime)
{
return dateTime.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
}
Your task will be solved with
return dateTime.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);

Related

How to convert a date in the form of a string with this format (yyyy-MM-dd HH:mm:ss) to a DateTime object of this format (dd-MM-yyyy HH:mm:ss)

I'm currently using C# and I want to convert a string like "2022-01-15 18:40:30" to a DateTime object with this format "15-01-2022 18:40:30". Below is what I've tried.
string stringDate = "2022-01-15 18:40:30";
string newStringDate = DateTime.ParseExact(date, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture).ToString("dd-MM-yyyy HH:mm:ss");
DateTime newDateFormat = DateTime.ParseExact(newStringDate, "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
But the result i keep getting is "2022-01-15T18:40:30"
Any help would be appreciated
As others pointed out, you have a internal data value for DateTime.
So, FOR SURE we suggest that you convert the string into that internal format.
Once you do that, then you are free to output that internal date time value to ANY kind of format and output you want.
Thus, we have this:
string stringDate = "2022-01-15 18:40:30";
DateTime MyDate = DateTime.ParseExact(stringDate,"yyyy-MM-dd HH:mm:ss",CultureInfo.InvariantCulture);
// now we can output convert to anything we want.
Debug.Print("Day of week = " + MyDate.ToString("dddd"));
Debug.Print("Month = " + MyDate.ToString("MM"));
Debug.Print("Month (as text) = " + MyDate.ToString("MMMM"));
// desired format
Debug.Print(MyDate.ToString("dd-MM-yyyy HH:mm:ss"));
And output is this:
DateTime date = Convert.ToDateTime("2022-01-15");
DateTime time = Convert.ToDateTime("18:40:30");
DateTime dt = Convert.ToDateTime(date.ToShortDateString() + " " + time.ToShortTimeString());
try this style
Try this one:
string stringDate = "2022-01-15 18:40:30";
Console.WriteLine((DateTime.Parse(stringDate)).ToString("dd-MM-yyyy HH:mm:ss"));
The DateTime object by itself does not have a specific "format".
The string representation gets created when you call the .ToString() function.
There are multiple overloads of the ToString function with which you can specify the format.

Split string on basis of "/"

I have a string:
string s = "1/09/2017 12:00:00 AM";
Output I want to show is 1/09/17 (basically short date).
And if
string s ="30/09/2017 12:00:00 AM"
Output I want to show is 30/09/17 (basically short date).
What I have tried is:
string[] values = s.Split('/');
string a = values[0]+"/"+values[1]+"/"+values[2].
I am confused how to get the 3rd part need help.
Use .NET built-in DateTime parsing.
For example:
string s = "1/09/2017 12:00:00 AM";
string format = "d/MM/yyyy hh:mm:ss tt";
DateTime parsedDateTime = DateTime.ParseExact(s, format, null);
string output = parsedDateTime.ToString("d/MM/yy"); //output = 1/09/17
More info:
DateTime.ParseExact method
DateTime.ToString method
My suggestion would be to use the inbuilt date datatype.
If that doesn't go with your requirement then I would suggest you to split the string based on the delimiter " "(blank space). Then pick the first part and proceed with your code.
You could use a substring like this
string s = "30/09/2017 12:00:00 AM";
string[] values = s.Split('/');
string a = values[0] + "/" + values[1] + "/" + values[2].Substring(2,2);
Adding to Paolo's anwer
string s = "1/09/2017 12:00:00 AM";
string format = "d/MM/yyyy hh:mm:ss tt";
DateTime parsedDateTime = DateTime.ParseExact(s, format, null);
string output = parsedDateTime.ToString("d/MM/yy");
string ss = output.Replace("-","/");
Console.Write(ss); //output is 1/09/17
This will exactly return the exact expected output
DateTime date = DateTime.ParseExact("1/09/2017 12:00:00 AM", "d/MM/yyyy hh:mm:ss tt", null);
Console.WriteLine(date.ToString("d/MM/yy"));
Convert your date string to DateTime and then use ToString overloaded method method with parameter Format Please find Fiddle

Parse C# string to hh:mm:ss

Given two strings
string date = "02Mar13";
string duration = "03.20min";
How do I parse them to DateTime and show them in the following format
string date = "02 March 2013";
string duration = "00:03:20";
I went through the list here but no one match my requirements.
You need to parse these using a Custom Date and Time format string, and output using one as well:
DateTime dt = DateTime.ParseExact(date + duration,
"ddMMMyymm.ss'min'",
CultureInfo.InvariantCulture);
string newDate = dt.ToString("dd MMMM yyyy");
string newDuration = dt.ToString("HH:mm:ss");
Things to note: I am using 'min' to represent the min literal in the string - this is part of custom format strings, allowing inner string literals.
string date = "02Mar13";
string duration = "03.20min";
DateTime newDate = DateTime.ParseExact(date + duration, "ddMMMyymm.ss\\min", null);
date = newDate.ToString("dd MMMM yyyy");
duration = newDate.ToString("hh:mm:ss");
How can produce the dateResult
string date = "02Mar13";
string duration = "03.20min";
var mat=Regex.Match(duration, "(.+?)min");
var dateResult = DateTime.ParseExact(date + mat.Groups[1].Value.Replace(".",":"), "ddMMMyyHH:mm", Thread.CurrentThread.CurrentCulture);
DateTime parsing is pretty much straightforward using DateTime.ParseExact:
DateTime.ParseExact(date, "ddMMMyy", null).ToString("dd MMMM yyyy"); // "02 March 2013"
As for the second part, if it is a duration semantically, then it is more suitable to use TimeSpan.ParseExact (although it required some fiddling with format strings):
TimeSpan.ParseExact(duration, "mm\\.ss'min'", null).ToString("hh\\:mm\\:ss"); // "00:03:20"

CONVERT MM/DD/YYYY HH:MI:SS AM/PM to DD/MM/YYYY in C#

How can I convert MM/DD/YYYY HH:MI:SS AM/PM into DD/MM/YYYY using C# ?I am using C#2008.
Thanks
Use TryParseExact to parse to a DateTime, then ToString with a format string to convert back...
DateTime dt;
if (DateTime.TryParseExact(value, "MM/dd/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture, DateTimeStyles.None,
out dt))
{
string text = dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
// Use text
}
else
{
// Handle failure
}
As the time part is irrelevant, you can truncate that before parsing and re-formatting:
date = DateTime.ParseExact(date.Substring(0, 10), "MM'/'dd'/'yyyy", CultureInfo.InvariantCulture).ToString("dd'/'MM'/'yyyy");
Edit:
As your comment reveals that you don't want a string as result, you should not format the date into a string, just get the date as a DateTime value:
Datetime dbDate = DateTime.ParseExact(date.Substring(0, 10), "MM'/'dd'/'yyyy", CultureInfo.InvariantCulture);
Now you can use the DateTime value in your code, wrapping it in a database driver type if needed.
If this is a DateTime object, you should be able to just select a different format.
If it is a string, use the following:
public string convert(string date){
string[] pieces = date.Split("/");
string day = pieces[1];
string month = pieces[0];
string year = pieces[2].split(" ")[0];
return day + "/" + month + "/" + year;
}

String to DateTime conversion as per specified format

I would like to have my end result in date format as per the specified format i.e YYMMDD how can i get this from a string given as below
string s="110326";
From string to date:
DateTime d = DateTime.ParseExact(s, "yyMMdd", CultureInfo.InvariantCulture);
Or the other way around:
string s = d.ToString("yyMMdd");
Also see this article: Custom Date and Time Format Strings
DateTime dateTime = DateTime.ParseExact(s, "yyMMdd", CultureInfo.InvariantCulture);
although id recommend
DateTime dateTime;
if (DateTime.TryParseExact(s, "yyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out dateTime))
{
// Process
}
else
{
// Handle Invalid Date
}
To convert DateTime to some format, you could do,
string str = DateTime.Now.ToString("yyMMdd");
To convert string Date in some format to DateTime object, you could do
DateTime dt = DateTime.ParseExact(str, "yyMMdd", null); //Let str="110719"

Categories