Csharp Swapping Dynamic values in string - c#

I want to swap two values in a STRING
This is an example of doing it with characters:
string str = "PQRQP";
var res= str.Select(a=> a == 'P' ? 'Q' : (a=='Q' ? 'P' : a)).ToArray();
str = new String(res);
Console.WriteLine(str);
But my string is 2/7/2019, where i want to swap the 2 and 7 each time but as these values are from user input i wont know what they will be before runtime.
Any help appreciated, thanks in advance !
-----------MY SOLUTION----------------
String values = DateRangePicker1.Value.ToString();
String startDate = values.Substring(0, 8);
String endDate = values.Substring(11, 8);
DateTime date = DateTime.ParseExact(startDate, "M/d/yyyy", CultureInfo.InvariantCulture);
DateTime date1 = DateTime.ParseExact(endDate, "M/d/yyyy", CultureInfo.InvariantCulture);
String newSDate = date.ToString();
String newEDate = date1.ToString();
String finalSDate = newSDate.Substring(0, 10);
String finalEDate = newEDate.Substring(0, 10);
I know this is slightly messy, but is working for me without affecting performance

This rather seems to be a localization issue (based on the fact that you are providing a string that looks like a date)
Is it possible that by just providing the correct date annotation that this would solve your problem?
DateTime.ParseExact(string)
for instance is a method that allows you to create a datetime object from a string, if you tell it what the string format is
example:
DateTime date = DateTime.ParseExact("2/1/2019", "M/d/yyyy", CultureInfo.InvariantCulture);
will provide a datetime object set to the first of febuary 2019. You can then convert the datetime object to a string with:
date.ToString("dd-MM-yy");
output: 01-02-19
Edit: if you have a range of acceptable formats, it is possible to provide an array of formats in string form.

You can use split to get the charachters you dont know.
Like this:
var sepratedInput = input.split('/');
var res= sepratedInput[1] +"/"+sepratedInput[0]+"/"+sepratedInput[2];
Console.write(res);

Related

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

Parse String date to specific format

This is a String date:
dob = reader.GetValue(7).ToString();` return like "12/2/2012"
But I want to convert (before passing it) to this format "2012212", I have tried
string newDate = dob.ToString("yyyMMdd")
But I got the following error:
The best overloaded method match for
'string.ToString(System.IFormatProvider)has some invalid arguments
any idea ?
Not Exact way of getting output but it will work.
string dob = "12/2/2012";
string[] d1 = dob.Split('/');
string s = d1[2] + d1[1] + d1[0];
You could use SqlDataReader.GetDateTime if underlying return type is DateTime
Then you just need..
reader.GetDateTime(7).ToString("yyyyMdd");
In case, if it is stored and received as a string then I would suggest converting to DateTime first and then look for specific format.
var date = DateTime.ParseExact(dob, "dd/M/yyyy",CultureInfo.InvariantCulture);
var formattedDate = date.ToString("yyyyMdd");
DateTime.ParseExact(reader.GetValue(7), "dd/M/dd", System.Globalization.CultureInfo.InvariantCulture).ToString("yyyyMMdd");
If you have a date in a String with the format "ddMMyyyy" and want to convert it to "yyyyMMdd" you could do like this:
DateTime dt = DateTime.ParseExact(dob, "ddMMyyyy",
CultureInfo.InvariantCulture);
dt.ToString("yyyyMMdd");
You can try below method to convert string to date.
IFormatProvider culture = new CultureInfo("en-US", true);
dob = DateTime.ParseExact(reader.GetValue(7).ToString(), "dd/MM/yyyy", culture).ToString("yyyyMMdd");
Thank you.

Remove '0' (Number) from DateTime Month and Day (String)

Can anybody tell me the best approach or solution on how I would do the following?
I have a DateTime (as String) in following format:
string test = "21.12.2013";
How could I now remove all zero's from the month and day but still 'keep' the DateTime Logic:
//Example 1
string input = "06.10.2013" // 6th October
string output = "6.10.2013" //only remove '0' from the day
//Example 2
string input = "01.09.2012" // 1st September
string output = "1.9.2012" //remove from month and day
//Example 3
string input = "20.10.2011" // 20th October
string output = "20.10.2011" //should (must) stay!
I can also parse to DateTime if that would be make it easier but yeah I hope you got my idea...
Any help appreciated!
Parsing your string into DateTime and getting it back to string using ToString with desired patter seems to be the easiest way to go:
public static string GetRidOfZeros(string input)
{
var dt = DateTime.ParseExact(input, "dd.MM.yyyy", CultureInfo.InvariantCulture);
return dt.ToString("d.M.yyyy", CultureInfo.InvariantCulture);
}
Little testing, with your sample data:
var inputs = new List<string> { "06.10.2013", "01.09.2012", "20.10.2011" };
var outputs = new List<string> { "6.10.2013", "1.9.2012","20.10.2011" };
if(outputs.SequenceEqual(inputs.Select(d => GetRidOfZeros(d))))
Console.WriteLine("Output is OK");
else
Console.WriteLine("Collections does not match.");
Prints Output is OK.
DateTime.Parse(input).ToString("d.M.yyyy")
As you said, parsing to DateTime first would probably make things easier, since then you can just use:
myDateTime.ToString("d.M.yyyy");
When you parse it you can use ToString to format it any way you like:
var date = "06.10.2013";
DateTime parsed = DateTime.ParseExact(date, "dd.MM.yyyy", CultureInfo.InvariantCulture);
var noZerosHere = parsed.ToString("d.MM.yyyy");
A decent "catch-all" method (that will work not just on DateTime but ANY kind of string) would be to split the string up, take out leading zeroes and then put the pieces back together again.
string input = "01.09.2012";
string[] values = input.Split(".");
string[] modifiedValues = values.Select(x => x.TrimStart('0');
string output = String.Join(".", modifiedValues);
You can adjust the delimiters for different representations of DateTime, e.g. those that use slashes (01/09/2012) or are written in a different order.

Join date and time strings into a DateTime

Given two strings with the following values:
31/05/2013 0:00:00
21:22
What's the most efficient way to join them into a DateTime data type to get:
31/05/2013 21:22
The time portion of the first string "0:00:00" is ignored, in favor of using the "time" from the second string.
Use a TimeSpan object and DateTime.Add(yourTimeSpan); e.g.
DateTime dt = new DateTime(2013,05,31);
var dts = dt.Add(new TimeSpan(0, 21, 22, 0, 0));
Extending the answer a bit, you can parse the date and time first, e.g.
DateTime dt = DateTime.Parse("05/31/2013 0:00:00");
TimeSpan ts = TimeSpan.Parse("21:22");
var dts = dt.Add(ts);
...keep in mind, I am not checking for bad date/time values. If you're unsure if the values are real dates/times, use DateTime.TryParse and handle appropriately.
As #George said, parse the first value as a DateTime and then another one as TimeSpan and then add the TimeSpan to first parsed value.
Another option is getting the substring of first 10 charachters of first value and concat it with a space with second value and parse it as DateTime.
Say that the first string is called one and the second one is called two, just do this:
DateTime result = DateTime.Parse(one).Date + DateTime.Parse(two).TimeOfDay;
string strDate = "31/05/2013 0:00";
string strTime = "21:22";
strDate = strDate.Replace("0:00", strTime);
DateTime date = Convert.ToDateTime(strDate);
If you are really dealing with only strings, then:
string strDate = "31/05/2013 0:00:00";
string strTime = "21:22";
string strDateTime = strDate.Split(' ')[0] + " " + strTime;
If you can safely assume you are getting 2 digit month and day, a 4 digit year, and a space after the date:
var date = "31/05/2013 0:00:00";
var time = "21:22";
var dateTime = DateTime.Parse(date.Substring(0,11) + time);
If the assumptions about the input format aren't solid you could use a regex to extract the date instead of Substring.
If you're starting out with just strings, you can just do this:
var dateString = "31/05/2013 00:00";
var timeString = "21:22";
var dateTimeString = dateString.Substring(0, 11) + timeString;
var output = DateTime.ParseExact(dateTimeString, "dd/MM/yyyy HH:mm", null);
Assuming you know for sure this format won't change (a dangerous assumption, to be sure), this will work. Otherwise, you'd have to parse the date and time strings separately and use conventional date manipulation as others suggested. For example:
var ci = System.Globalization.CultureInfo.CreateSpecificCulture("en-GB");
var dateString = "31/05/2013 00:00";
var timeString = "21:22";
var output = DateTime.Parse(dateString, ci) + TimeSpan.Parse(timeString, ci);
DateTime date = DateTime.ParseExact("31/05/2013 0:00:00", "dd/MM/yyyy h:mm:ss", CultureInfo.InvariantCulture);
TimeSpan span = TimeSpan.ParseExact("21:22", "t", CultureInfo.InvariantCulture);
DateTime result = date + span;

Parsing a date string to get the year

I have a string variable that stores a date like "05/11/2010".
How can I parse the string to get only the year?
So I will have another year variable like year = 2010.
You can use the DateTime.Parse Method to parse the string to a DateTime value which has a Year Property:
var result = DateTime.Parse("05/11/2010").Year;
// result == 2010
Depending on the culture settings of the operating system, you may need to provide a CultureInfo:
var result = DateTime.Parse("05/11/2010", new CultureInfo("en-US")).Year;
// result == 2010
This should work for you.
string myDate = "05/11/2010";
DateTime date = Convert.ToDateTime(myDate);
int year = date.Year;
If the date string format is fixed (dd/MM/yyyy), I would like to recommend you using DateTime.ParseExact Method.
The code:
const string dateString = "12/02/2012";
CultureInfo provider = CultureInfo.InvariantCulture;
// Use the invariant culture for the provider parameter,
// because of custom format pattern.
DateTime dateTime = DateTime.ParseExact(dateString, "dd/MM/yyyy", provider);
Console.WriteLine(dateTime);
Also I think it might be a little bit faster than DateTime.Parse Method, because the Parse method tries parsing several representations of date-time string.
you could also used Regex to get the year in the string "05/11/2010"
public string getYear(string str)
{
return (string)Regex.Match(str, #"\d{4}").Value;
}
var result = getYear("05/11/2010");
2010
Variant of dtb that I use:
string Year = DateTime.Parse(DateTime.Now.ToString()).Year.ToString();

Categories