Split string on basis of "/" - c#

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

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.

Converting a String to DateTime with new format

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);

Reading date from string format

I have to read a date in this format in c#
yyyy/MM/dd HH:mm:ss
I cannot change the format because is written by another application
The date is a string like
2009/11/17 12.31.35
How i can read this format without parsing it(without split if possible)
thanks
I cannot change the format because is written by another application
Solution 1: You don't need to change the format for reading it.
Try This:
DateTime dt;
DateTime.TryParseExact(date, "yyyy/MM/dd HH.mm.ss",
CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
OR
How i can read this format without parsing it(without split if
possible)
Solution 2: If you want to extract the values from the date string.
Try This:
string str = "2009/11/17 12.31.35";
string year = str.Substring(0, 4); //2009
string month = str.Substring(5, 2); //11
string date = str.Substring(8, 2); //17
string Hours = str.Substring(11, 2); //12
string minutes = str.Substring(14, 2);//31
string seconds = str.Substring(17, 2);//35
Use DateTime.ParseExact, where you can supply your custom date format
Try replacing . with : an then ParseExtract
string dt= "2009/11/17 12.31.35";
var dt2= ss.Replace('.', ':');
DateTime d = DateTime.ParseExact(dt2, "yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture);
or just
DateTime d = DateTime.ParseExact("2009/11/17 12.31.35", "yyyy/MM/dd HH.mm.ss", CultureInfo.InvariantCulture);

Converting date to datetime

I have a date in string form and input timeformat(ex: hh:mm tt). I want to convert date to dateime string. Below is my code :
string inputDate = "01/02/11";
string inputTimeFormat = "hh:mm tt";
Regex rgx1 = new Regex("tt");
string time1 = rgx1.Replace(inputTimeFormat, "AM");
Regex rgx = new Regex("[^ :AM]");
string time = rgx.Replace(time1, "0");
string dateTime = string.Format("{0} {1}", inputDate, time);
//output: 01/02/11 00:00 AM
Right now it is giving output in datetime string format, Is there any better way of doing the same?
EDIT: I need datetime in string format here and after that I can apply Datetime.TryParseExact
You're looking for the DateTime type:
DateTime.Parse("01/02/11").ToString("hh:mm tt")
DateTime.ParseExact('your date string', format, culture)
Am I missing something?

How to convert date format to DD-MM-YYYY in C#

How to convert date format to DD-MM-YYYY in C#? I am only looking for DD-MM-YYYY format not anything else.
string formatted = date.ToString("dd-MM-yyyy");
will do it.
Here is a good reference for different formats.
According to one of the first Google search hits:
http://www.csharp-examples.net/string-format-datetime/
// Where 'dt' is the DateTime object...
String.Format("{0:dd-MM-yyyy}", dt);
Here is the Simplest Method.
This is the String value: "5/13/2012"
DateTime _date;
string day = "";
_date = DateTime.Parse("5/13/2012");
day = _date.ToString("dd-MMM-yyyy");
It will output as: 13-May-2012
string formattedDate = yourDate.ToString("dd-MM-yyyy");
DateTime dt = DateTime.Now;
String.Format("{0:dd-MM-yyyy}", dt);
DateTime s1 = System.Convert.ToDateTime(textbox.Trim());
DateTime date = (s1);
String frmdt = date.ToString("dd-MM-yyyy");
will work
DateTime dt = DateTime.Now;
String.Format("{0:dd-MM-yyyy}", dt);
First convert your string into DateTime variable:
DateTime date = DateTime.Parse(your variable);
Then convert this variable back to string in correct format:
String dateInString = date.ToString("dd-MM-yyyy");
Here we go:
DateTime time = DateTime.Now;
Console.WriteLine(time.Day + "-" + time.Month + "-" + time.Year);
WORKS! :)
From C# 6.0 onwards (Visual Studio 2015 and newer), you can simply use an interpolated string with formatting:
var date = new DateTime(2017, 8, 3);
var formattedDate = $"{date:dd-MM-yyyy}";
Do you have your date variable stored as a String or a Date type?
In which case you will need to do something like
DateTime myDate = null;
DateTime.TryParse(myString,myDate);
or
Convert.ToDateTime(myString);
You can then call ToString("dd-MM-yyyy") on your date variable
I ran into the same issue. What I needed to do was add a reference at the top of the class and change the CultureInfo of the thread that is currently executing.
using System.Threading;
string cultureName = "fr-CA";
Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureName);
DateTime theDate = new DateTime(2015, 11, 06);
theDate.ToString("g");
Console.WriteLine(theDate);
All you have to do is change the culture name, for example:
"en-US" = United States
"fr-FR" = French-speaking France
"fr-CA" = French-speaking Canada
etc...
The problem is that you're trying to convert a string, so first you should cast your variable to date and after that apply something like
string date = variableConvertedToDate.ToString("dd-MM-yyyy")
or
string date = variableConvertedToDate.ToShortDateString() in this case result is dd/MM/yyyy.
dateString = "not a date";
// Exception: The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.
DateTime dateTime11; // 1/1/0001 12:00:00 AM
bool isSuccess2 = DateTime.TryParseExact(dateString, "MM/dd/yyyy", provider, DateTimeStyles.None, out dateTime11);
var dateTimeString = "21‎-‎10‎-‎2014‎ ‎15‎:‎40‎:‎30";
dateTimeString = Regex.Replace(dateTimeString, #"[^\u0000-\u007F]", string.Empty);
var inputFormat = "dd-MM-yyyy HH:mm:ss";
var outputFormat = "yyyy-MM-dd HH:mm:ss";
var dateTime = DateTime.ParseExact(dateTimeString, inputFormat, CultureInfo.InvariantCulture);
var output = dateTime.ToString(outputFormat);
Console.WriteLine(output);
Try this, it works for me.
you could do like this:
return inObj == DBNull.Value ? "" : (Convert.ToDateTime(inObj)).ToString("MM/dd/yyyy").ToString();

Categories