How can i format the string to add '-' between the numbers? - c#

var startIndexTimeDate = file.Path.IndexOf("time=") + "time=".Length;
var lengthTimeDate = file.Path.IndexOf("&", startIndexTimeDate) - startIndexTimeDate;
var timeDate = file.Path.Substring(startIndexTimeDate, lengthTimeDate);
What i'm getting in timeDate for example is:
201702012015
And i want to format it to be:
01-02-20-15-2017
Not only for this number for every time i will do this code. The format should be this way since i want to create a directory of this format.
01-02-20-15-2017
Then i will want to read it back from the hard disk the directory name to a List but this time the string should be format as a date time for example:
"01/02/2017 at 20:15"
So when i read it back i want to display it nicer to the user.
The directory on the hard disk will be in format of
01-02-20-15-2017
but when getting the directory name back to a List the format should be
"01/02/2017 at 20:15"

I would suggest you to parse DateTime object from your string, and after that format it in any way you want:
var s = "201702012015";
var date = DateTime.ParseExact(s, "yyyyMMddHHmm", CultureInfo.InvariantCulture);
var dirName = date.ToString("dd-MM-HH-mm-yyyy"); //01-02-20-15-2017
Then do the same when reading directory
var date = DateTime.ParseExact(dirName, "dd-MM-HH-mm-yyyy", CultureInfo.InvariantCulture);
var nameInList = date.ToString("dd/MM/yyyy a\\t HH:mm"); //01/02/2017 at 20:15

Related

Convert date format 01/05/2018 and 01/may/2018 to (dd/mm/yyyy) format and save same format into excel using c#

I Have two type of date formats like 01/05/2018 and 01/may/2018. I want to convert both formats into (dd/MM/yyyy), how do I convert it and save into excel file. I have a problem in saving data into excel, the save not proper format, its change like a month comes first and sometimes date come first
the code is:-
mystring=mystring.tostring.parse("dd/MM/yyyy")
I had similar problem and I tried the code below
DateTime date = DateTime.Now;
string formattedDate = date.ToString("dd'/'MM'/'yyyy");
I believe you have to do:
targetRange.NumberFormat = "dd/MM/yyyy";
Where targetRange is either the Cell or Column that you want to have the required date format
The format must also be something that Excel understands and this is not always the same as what C# uses
You can provide several formats when using DateTime.ParseExact. So you can parse initial string into DateTime and then format the DateTime into required format.
string[] tests = new string[] {
"01/05/2018",
"01/may/2018",
};
string[] formats = new string[] {
"d/M/yyyy", // try this format first
"d/MMMM/yyyy", // on fail try this one etc.
};
string[] results = tests
.Select(item => DateTime.ParseExact(item,
formats,
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeLocal))
.Select(date => date.ToString("dd'/'MM'/'yyyy")) // '/' - to preserve /
.ToArray();
Console.Write(Environment.NewLine, results);
Outcome:
01/05/2018
01/05/2018

Parsing a DateTime string in C# with strange characters

I have a dateTime string as follows "\"2017-09-20T02:55:15.000Z\"". I want to parse it in C#.
DateTime gpsddt
string date = "\"2017-09-20T02:55:15.000Z\"";
var result = DateTime.TryParse(date, out gpsddt);
result is false. I don't know how to parse the above string. I got this string from a gpsd daemon. I can't find any format specifier that matches this datetime string here
The string is currently "2017-09-20T02:55:15.000Z", but it needs to be 2017-09-20T02:55:15.000Z to parse correctly. As #Chetan suggested in the comment, you need to strip out the " characters.
Add this line before parsing.
date = date.Replace("\"", "");
Alternatively, the DateTime.TryParseExact allows you to specify the source format. However it does require you to consider a lot more factors such as culture and style to use as well.
result = DateTime.TryParseExact(date, "\"\\\"\"yyyy-MM-ddTHH:mm:ss.fffZ\"\\\"\"", new CultureInfo("en-AU"), DateTimeStyles.AssumeUniversal, out gpsddt);
It is just a simple matter of doing this:
DateTime gpsddt;
string date = "\"2017-09-20T02:55:15.000Z\"";
var result = DateTime.TryParse(date.Trim('"'), out gpsddt);

System.FormatException in mscorlib.dll for DateTime conversion

I'm trying to convert an Active Directory attribute (whenCreated) into DateTime then String, but I keep getting a FormatException, any ideas why? Here is the code:
string format = "YYYYMMDDHHMMSS.0Z";
DateTime dt = DateTime.ParseExact(sResult.Properties["whenCreated"][0].ToString(),format,CultureInfo.InvariantCulture);
string whenCreated = dt.ToString();
Also, sResult.Properties["whenCreated"][0].ToString() is the result from an Active Directory search (the date retrieved) and has the String (Generalized Time) syntax.
The DateTime.ParseExact method expects a format string, that tells it where in the input string is which component of a valid date. Your format of 'd' does not meet this criteria. I don't know the content of your input (would help if you add it). But lets assume it would be "2017/31/05 10:27:45" for today. Your format string would then have to be: "yyyy/dd/MM HH:mm:ss"
DateTime dt = DateTime.ParseExact("2017/31/05 10:27:45","yyyy/dd/MM HH:mm:ss",CultureInfo.InvariantCulture);
According to the documentation linked by the OP:
The format for the Generalized-Time syntax is "YYYYMMDDHHMMSS.0Z". An example of an acceptable value is "20010928060000.0Z"
And:
If the time is specified in a time zone other than GMT, the differential between the time zone and GMT is appended to the string instead of "Z" in the form "YYYYMMDDHHMMSS.0[+/-]HHMM". An example of an acceptable value is "20010928060000.0+0200"
So you'd need two format strings in order to parse the strings, like this:
string adDate = "20010928060000.0Z";
string adDate2 = "20010928060000.0+0200";
string format = "yyyyMMddhhmmss.0Z";
string format2 = "yyyyMMddhhmmss.0zzz";
DateTime dtdtdt = DateTime.ParseExact(adDate2, new string[] { format, format2 },
CultureInfo.InvariantCulture,DateTimeStyles.None);

How can i create this format of date time directory but with my format?

The test i did is:
string date = DateTime.Now.ToString("ddd dd.MM.yyyy");
string time = DateTime.Now.ToString("HH.mm tt");
string format = "{0} from {1} At {2}";
string cp = string.Format(format, "", date, time);
Directory.CreateDirectory(#"c:\\temp\\" + cp);
The result in the variable cp is: from Fri 20.01.2017 At 09.27 AM
And there is no problem to create this directory.
This is my code:
for (int i = 0; i < countriesNames.Count(); i++)
{
string pathDateTime = urls[0].Substring(48, 12);
string pathDateTimeLast = urls[urls.Count - 1].Substring(48, 12);
var d = DateTime.ParseExact(pathDateTime, "yyyyMMddHHmm", CultureInfo.InvariantCulture);
var e = DateTime.ParseExact(pathDateTimeLast, "yyyyMMddHHmm", CultureInfo.InvariantCulture);
string country = countriesNames[i].Substring(15);
string f = "{0} from {1} At {2} until {3}";
string countryPath = countriesMainPath + "\\" + country + "\\" + string.Format(f, "", d,e);
if (!Directory.Exists(countryPath))
{
Directory.CreateDirectory(countryPath);
}
countryPaths.Add(countryPath);
}
The way i did it with the 'f' variable is not right and not working fine give me exception.
In my code in the variable 'd' there is 20/01/2017 05:15:00
And in variable 'e' 20/01/2017 07:30:00
But i can't create this directories.
So i want to format my date and time after extracting them to be like the format in the first example: from Fri 20.01.2017 At 09.27 AM but with my date and time.
For example my directory should be something like:
from Fri 20.1.2017 At 05:15 AM Until 20.1.2017 At 07:30 AM
Then to create this directory: "from Fri 20.1.2017 At 05:15 AM Until 20.1.2017 At 07:30 AM"
The question is how do i format my dates and times after parsed to this format ?
You are trying to create a path by formatting dates using your current locale's default (long) format. In most countries the date separator is / and the time separator is always :. This results in invalid paths.
It's a bit hard to understand what format you want to use, since you mix calls to String.Format and concatenate the results. It seems that the original path should be:
var cp=String.Format(#"c:\temp\From {0:ddd dd.MM.yyyy} At {0:HH.mm tt}",DateTime.Now);
or
var root="c:\temp\";
var partialPath = String.Format("From {0:ddd dd.MM.yyyy} At {0:HH.mm tt}",DateTime.Now)
var cp=Path.Combine(root,partialPath);
You don't need to format each component separately. If you check the documentation of String.Format you'll see that you can use a composite format string for each placeholder.
The country path seems to be
var partialPath = String.Format(#"{0}\from {1:ddd dd.MM.yyyy} At {1:HH.mm tt} until {2:HH.mm tt}",
country,d,e);
var countryPath =Path.Combine(countriesMainPath,partialPath);
That said, I wouldn't use that date format. The resulting folder names can't be sorted in a meaningful way making it difficult for users to find folders by date. I'd use the yyyy-MM-dd format, or yyyy-MM-dd ddd if the name of the day is really necessary.

Date time format in C#

i have a string like "14-Nov-2014" , i want to convert this string to this 14.11.2014 format.
after converting i want to add 14 days to above date.
given date is not Datetime format.
Old date="14-Nov-2014"
new date=14.11.2014
is there any way to do in c#?
Assuming,
var myString = "14-Nov-2014";
First parse the string, most likely using DateTime.ParseExact. Assuming a few things about the format you have, you could do the following. Note you most likely should specify the proper culture for the third argument:
var dateTime = DateTime.ParseExact(myString, "dd-MMM-yyyy", null);
Then you can add 14 days to it easily:
var dateTime = dateTime.AddDays(14);
To get a new string in a different format just use ToString with a format string. For example:
var myNewString = dateTime.ToString("d.MM.yyyy");

Categories