C# How to seperate string character by character [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have parsed a response from an Api into date string, and its data. The date string shows as:
"201710010900000"
What i am trying to to do is convert this into a format that can be read by date mm/dd/yyyy to do this
i must grab the first 4 letters as year, the next 2 as month, the next 2 as day. ideally call these into separate strings date,month,day. that way it can be converted into one string.
string reDate = (month + "/" + day + "/" + year);
Is there a way to call each character of the string individually, Or what would be the best way to do this?

A string is an array of characters. Just iterate over it or use an indexer, eg:
var someChar="201710010900000"[0];
You don't need to do that if you want to parse this as a date though, as you should. Just use DateTime.ParseExact, eg:
var input="201710010900000";
var format="yyyyMMddHHmmssf";
var date=DateTime.ParseExact(input,format,CultureInfo.InvariantCulture);
Other overloads allow you to specify multiple formats, eg this one.
ParseExact will throw an exception if the conversion fails. If you expect this to be a common occurence, you can use TryParseExact :
var styles=DateTimeStyles.None;
var culture=CultureInfo.InvariantCulture;
if (DateTime.TryParseExact(input,format,culture,styles,out var date))
{
//Do something with the date
}
Once you have the DateTime value you can use the standard string formatting mechanisms to generate a string with the format you want, in the culture you want.
If you want a US-style short date, you can write any of the following :
var targetCulture = CultureInfo.GetCultureInfo("en-US");
var text1=date.ToString("d",targetCulture);
var text2=String.Format(targetCulture,"This is my date: {0:d}",result);

DateTime.ParseExact or DateTime.TryParseExact were made for this purpose:
DateTime dt;
bool validDate = DateTime.TryParseExact("201710010900000", "yyyyMMddHHmmssf", null, DateTimeStyles.None, out dt);
To separate the day, month etc you just need to use the available properties:
int year = dt.Year;
int month = dt.Month;
int day = dt.Day;
int hour = dt.Hour;
If you want the return string with this format: month+"/"+ day+"/"+year use DateTime.ToString:
string returnString = dt.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);

ParseExact into DateTime and then represent it as a String:
string source = "201710010900000";
string result = DateTime
.ParseExact(source, "yyyyMMddHHmmssf", CultureInfo.InvariantCulture)
.ToString("MM'/'dd'/'yyyy");

If your plan is to 'iterate' over the response you can try something like:
var input = "201710010900000";
var year = Convert.ToInt32(input.Substring(0, 4));
var month = Convert.ToInt32(input.Substring(4, 2));
var day = Convert.ToInt32(input.Substring(6, 2));
var hour = Convert.ToInt32(input.Substring(8, 2));
var minutes = Convert.ToInt32(input.Substring(10, 2));
var seconds = Convert.ToInt32(input.Substring(12, 2));
var date = new DateTime(year, month, day, hour, minutes, seconds);
Console.WriteLine(date);
I hope it helps,
Another aproach is to create a new date specifying the imput format as somebody else answered here (and to be fair a very good aproach).
Juan

Related

Formatting datetime variable [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am trying to convert and store a date in the form of String into datetime variable.
String fromdate= "02-JUN-2014";
DateTime dFromDate = Convert.ToDateTime(fromdate);
This dfromDate is used in another function which expects date to be in 02-JUN-2014 format.But since dfromDate storing the date as 06/02/2014, there is a format exception.
You can use ParseExact()
String fromdate="02-JUN-2014";
DateTime dFromDate = DateTime.ParseExact(fromdate, "dd-MMM-yyyy",CultureInfo.InvariantCulture)
Wrap fromDate in quotes:
var fromdate = "02-JUN-2014";
var dFromDate = Convert.ToDateTime(fromdate);
I am not to sure of the entire context but you could always use the folowing to create a new date:
DateTime thisDate1 = new DateTime(2011, 6, 10);
Console.WriteLine("Today is " + thisDate1.ToString("MMMM dd, yyyy") + ".");
// The example displays the following output:
// Today is June 10, 2011.
You want to use DateTime.ParseExact i.e.
DateTime dFromDate = DateTime.ParseExact(fromdate, "dd-MMM-yyyy", CultureInfo.InvariantCulture);
You may need to specific a culture for your language if you are not US (CultureInfo.InvariantCulture is a special form of US).
Convert.ToDateTime uses standard date and time format of your CurrentCulture and looks like dd-MMM-yyyy is not one of them.
You can use ParseExact method with english-based culture like InvariantCulture.
String fromdate = "02-JUN-2014";
DateTime dFromDate = DateTime.ParseExact(fromdate, "dd-MMM-yyyy",
CultureInfo.InvariantCulture);
Using DateTime.ParseExactmight work, and itis the best option if you know exactly the format string, but you could also set the current CultureInfo for the call:
String fromdate= "02-JUN-2014";
DateTime dFromDate = Convert.ToDateTime(fromdate, CultureInfo.CurrentCulture);
Or:
String fromdate= "02-JUN-2014";
DateTime dFromDate = Convert.ToDateTime(fromdate, new CultureInfo("es-ES"));
String fromdate= "02-JUN-2014";
DateTime dFromDate = DateTime.ParseExact(fromdate,"dd-MMM-yyyy",
CultureInfo.InvariantCulture);
Use ParseExact method.
Your first problem might be, that you need to assign a string like this:
String fromdate = "02-JUN-2014";

How to find number of days from two string type dates? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have two text box dates (8/11/2014) and (9/11/2014). I want to find the number of days between these two dates. I am getting some string error message. Please help me..
Just parse both dates and then substract them and count total days like this:
DateTime date1 = DateTime.ParseExact(dateString1, "d/M/yyyy", CultureInfo.InvariantCulture);
DateTime date2 = DateTime.ParseExact(dateString2, "d/M/yyyy", CultureInfo.InvariantCulture);
var days = (int)(date2-date1).TotalDays;
I feel taking risk to answer this but..
You can use DateTime.ParseExact or DateTime.TryParseExact methods to parse your strings and subtract each other and use TimeSpan.TotalDays property. You can use TimeSpan.Days property as well if you are interested in the total days as an int rather than a double.
string txtdate = "8/11/2014";
DateTime dt;
if(DateTime.TryParseExact(txtdate, "d/MM/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
}
string txtdate1 = "9/11/2014";
DateTime dt1;
if(DateTime.TryParseExact(txtdate1, "d/MM/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt1))
{
}
var totaldays = (dt1 - dt).Days; // 1
You said;
I need output as 8/11/2014-9/11/2014=1. But I applied your code it
shows output like 1.0?
I told you TotalDays property returns double and Days property returns int. But besides that, you seems like a result as 9/11/2014 - 8/11/2014 = 1 instead of just 1. In such a case, you can use string.Format like;
var result = string.Format("{0} - {1} = {2}",
dt1.ToString("d/MM/yyyy", CultureInfo.InvariantCulture),
dt.ToString("d/MM/yyyy", CultureInfo.InvariantCulture),
totaldays);
result will be 9/11/2014 - 8/11/2014 = 1

How to convert date to 'ccyymmddhhmmss' format?

How to convert date to 'ccyymmddhhmmss' format in c#?
You might want to try this... I don't know if cc is included, so I solved for the cc.
DateTime time = DateTime.Now;
string format = "yyMMddhhmmss";
Console.WriteLine(((Convert.ToInt32(time.ToString("yyyy")) / 100) + 1).ToString() + time.ToString(format));
For "yyMMddhhmmss".....Try this...And don't forget that capital M is Month and lower case m is minutes.
DateTime dt = Convert.ToDateTime("8 Oct 10 19:00");
Console.WriteLine(dt.ToString("yyMMddhhmmss"));
From what I understand from your question, you want to format a c# date object to the specified format?
The easiest way to do that is by using the date.ToString("yyyyMMddHHmmss") - where date is the Date Object... There are several choices to this - like having 12-hour instead of 24-hour etc. The best option is to read through http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx and set what you need.
Hope this helps.
#Chris_techno25: I took the freedom to extend your answer:
If we stick to the question of Narashima, he wants the format ccyymmddhhmmss.
So I've scratched up this extension method:
public static string IncludeCentury(this DateTime sourceDate, bool replace)
{
var source = String.Format("{0}/{1}", sourceDate.Year / 100 + 1, sourceDate);
if(replace)
return Regex.Replace(source, "[^0-9]", "");
else
return source;
}
Usage:
var includingCentury = DateTime.Now.IncludeCentury(true)
var includingCentury = DateTime.Now.IncludeCentury(false)
Output:
21218201491410
21/2/18/2014 9:18:10 AM

String To DateFormat Conversion

Is there any way I don't have to specify the number of digits in day/month/year?
For e.g 1/2/1991
I want a method which satisfies both 1/2/1991,11/3/1990,12/12/1991
I don't know how many digits will be there in either month, year, or days.
My code is
string copy = splittedData[0] + splittedData[1] + splittedData[2];//date+month+year
DateTime datetime = DateTime.ParseExact(copy, "ddMMyyyy", CultureInfo.InvariantCulture);
DateTime dateAndTime = datetime;
The problem is the number of digits in splitted data array are not known to me and thus the above format "ddMMyyyy" give me exception on some cases.
Since you already have the day month and year then just create a date with the three of them like so;
DateTime date = new DateTime(year, month, day);
No parsing is necessary. You already have all the fields you want to create the date, and you dont need to put it into a special format to create a date.
If you are not sure the if the input is valid, then wrap the creation in a try/catch block to catch an ArgumentOutOfRangeException should it should occur.
Since you updated your question with the code you have, you can concatenate date components with a separator like:
string copy = splittedData[0] + "/" + splittedData[1] + "/" + splittedData[2];
Later you can do:
DateTime dt = DateTime.ParseExact(copy, "d/M/yyyy", CultureInfo.InvariantCulture);
I used the format "d/M/yyyy" with single d and M which would account for both single/double digit day/month.
So it will work for dates like:
01/01/2013
1/01/2013
22/09/2013
02/9/2013
DateTime.ParseExact is specifically intended to not allow what you are asking for. DateTime.Parse will allow it, though.
You say you have the 3 parts as separate strings -- if you insert the /'s and parse, it should succeed (InvariantCulture expects the order month-day-year):
string datetimeString = string.Join("/", new[] {month, day, year});
DateTime datetime = DateTime.Parse(datetimeString, CultureInfo.InvariantCulture);
Or you could convert them to integers and construct a DateTime directly:
DateTime datetime = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), Convert.ToInt32(day));
What #n00b said. You've already got the individual components of the date: why are you globbing them back together just so you can call DateTime parsing routines? Just do something like this:
private static DateTime StringToDateTime( string year , string month , string day )
{
int yyyy = int.Parse(year) ;
int mm = int.Parse(month) ;
int dd = int.Parse(day) ;
DateTime dt = new DateTime(yyyy,mm,dd) ;
return dt ;
}
As an added bonus, The above code will probably run faster than DateTime.Parse() or DateTime.ParseExact().

Formatting any string to string "yyyy/MM/dd" [duplicate]

This question already has answers here:
Date formatting yyyymmdd to yyyy-mm-dd
(9 answers)
Closed 5 years ago.
I have many strings like "20120117" and "20120321". I need to convert it in a new string with this format: "2012/01/17" and "2012/03/21". So, there is a way to do this?
I try:
string dateString = string.format("{0:d", "20120321");
and
string dateString = string.format("{0:yyyy/MM/dd", "20120321");
and
string dateString = int.Parse("20120321").ToString("yyyy/MM/dd");
I all cases i don't reach my goal. =/
So, i can i do this?
OBS: There is a way to do that without parse to datetime?
You have to parse those values in DateTime objects first.
Example :
DateTime dt = DateTime.ParseExact("20120321", "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
var result = dt.ToString("yyyy/MM/dd");
Edit after your comments on other answers:
if you don't like parsing because it may throw excepations, you can always use TryParse, like this:
DateTime dt;
bool success = DateTime.TryParseExact("20120321", "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dt);
if (success)
{
var result = dt.ToString("yyyy/MM/dd");
}
Edit 2: Using TryParseExact with multiple formats:
DateTime dt;
string[] formats = { "yyyyMMdd", "yyyy" };
bool success = DateTime.TryParseExact("20120321", formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dt);
if (success)
{
var result = dt.ToString("yyyy/MM/dd");
Console.WriteLine(result);
}
It will produce 2012/03/21 when using "20120321" as input value, and 2012/01/01 when using 2012 as input value.
DateTime.ParseExact("20120321", "yyyyMMdd", CultureInfo.CurrentCulture).ToString("yyyy/MM/dd")
You could parse the string but this method gives you validation without any extra code. Imagine receiving "20120230", "20110229", or any other invalid date.
From your comments:
There is a way to do that without parse to datetime?
Yes, absolutely. If you really want to propagate bad data through your system rather than highlighting that it's incorrect, you could definitely use:
// Make sure we'll always be able to get a result whatever the input.
string paddedInput = input + "????????";
string mightBeBadWhoKnows = string.Format("{0}/{1}/{2}",
paddedInput.Substring(0, 4), // The year, if we're lucky
paddedInput.Substring(4, 2), // The month, if we're lucky
paddedInput.Substring(6, 2)); // The day, if we're lucky
But why wouldn't you want to spot the bad data?
You absolutely should parse the data. If you want to be able to continue after receiving bad data having taken appropriate action, use DateTime.TryParseExact. If you're happy for an exception to be thrown, use DateTime.ParseExact. I'd suggest using the invariant culture for both parsing and formatting, unless you really want a culture-sensitive output.
Use DateTime.ParseExact to convert to a DateTime, then use ToString on that instance to format as you desire.
DateTime.ParseExact(dateString, "yyyyMMdd").ToString("yyyy/MM/dd");
EDIT: using Insert:
EDIT2: Fixed bugs :-)
var newString = dateString.Insert(4, "/").Insert(7, "/");
Just use string operations to insert the slashes:
string input = "20120321";
string dateString =
input.Substring(0, 4) + "/" +
input.Substring(4, 2) + "/" +
input.Substring(6);
or
string dateString = input.Insert(6, "/").Insert(4, "/");
If it's a date, try this:
DateTime.ParseExact("20120321","yyyyMMdd", null).ToString("yyyy/MM/dd", System.Globalization.DateTimeFormatInfo.InvariantInfo)
try this;
string dateString = DateTime.ParseExact("20120321", "yyyyMMdd",
null).ToShortDateString();
If your data is always in the same format and if you don't need to validate it, you can use the following snippet to avoid parsing it with DateTime
var strWithInsert = input.Insert(4,"/").Insert(7,"/");

Categories

Resources