How to find multiple substrings - c#

I have stored date of birth var char format:
Example: 1989-8-15
I want to find out sub string from it i.e I want separate year, month and date. I have tried it with following code:
string dateOfbirth = (string)(DataBinder.Eval(e.Item.DataItem, "dob"));
int length = (dateOfbirth).Length;
int index1 = dateOfbirth.IndexOf('-');
int index2 = dateOfbirth.IndexOf('-', index1 + 1);
string year = dateOfbirth.Substring(0, index1);
string month = dateOfbirth.Substring(index+1, index2-1);
string day = dateOfbirth.Substring(index2, length);
I am getting an error. Please suggest a solution. Thanks in advance.

You can try this
string [] date = dateOfbirth.Split('-');
string year = date[0];
string month = date[1];
string day = date[2];

DateTime dob = DateTime.ParseExact("1989-8-15","yyyy-M-dd",null);
Console.WriteLine(dob.Year);
Console.WriteLine(dob.Month);
Console.WriteLine(dob.Day);
Clean and easy.
UPD: changed Parse to ParseExact with a custom date format

I hope this will help:
string st= "1989-8-15"; /
string st = (string)(DataBinder.Eval(e.Item.DataItem, "dob"));
string [] stArr = st.Split('-');
So, you now have an array with dob items.

To actually answer your question:
string dateOfbirth = "1989-8-15";
int length = (dateOfbirth).Length;
int index1 = dateOfbirth.IndexOf('-');
int index2 = dateOfbirth.IndexOf('-', index1 + 1);
string year = dateOfbirth.Substring(0, index1);
string month = dateOfbirth.Substring(index1 + 1, index2 - index1 - 1);
string day = dateOfbirth.Substring(index2 + 1, length - index2 - 1);
It's just a matter of providing the correct parameters to the Substring method.
Using dateOfBirth.Split('-') would probably be at better solution for your problem, though.

Use TryParseExact to avoid exception due to different culture settings
DateTime dateValue;
var dateString="1989-08-15";
if(DateTime.TryParseExact(dateString, "yyyy-MM-dd", CultureInfo.InvariantCulture,DateTimeStyles.None, out dateValue))
{
// parse successfull
Console.WriteLine(dateValue.Year);
Console.WriteLine(dateValue.Month);
Console.WriteLine(dateValue.Day);
}

Related

convert standard date to standard persian date in c#

I have a function that can convert the standard date to persian standard date as you can see here:
public string ConvertToPersianToShow(DateTime datetime)
{
PersianCalendar persian_date = new PersianCalendar();
string date;
string year = Convert.ToString(persian_date.GetYear(datetime));
string Month = Convert.ToString(persian_date.GetMonth(datetime));
string day = Convert.ToString(persian_date.GetDayOfMonth(datetime));
date = year+"/" + Month + "/" + day;
return date;
}
But i have a problem with these outputs:
1394/5/1
1394/12/8
1395/7/12
These outputs should be like this :
1394/05/01
1394/12/08
1395/07/12
I can count the digit numbers of the day and month but i thing it isn't the best way to do that .could you please give me some help about how can i change these kind of outputs using stringformat?
All you need to do is add a leading zero. .ToString can be used.
string Month = persian_date.GetMonth(datetime).ToString("D2");
string day = persian_date.GetDayOfMonth(datetime).ToString("D2");
You can use this function:
private static string UpdateDate(string date)
{
date.PadLeft(2, '0');
}
date = year+"/" + UpdateDate(Month) + "/" + UpdateDate(day);

How can I subtract datetimes to give the results in the format I require?

I'm trying to subtract between two dateTimes in a way that I'll see all totaled hours.(including mm and ss if theres any)
for Example:
TimeSpan j = DateTime.Parse("06/05/2015 12:00:00").Subtract(DateTime.Parse("04/05/2015 14:00:00"));
I want to return a string that contains "46:00:00"
TimeSpan j = DateTime.Parse("06/05/2015 12:00:00").Subtract(DateTime.Parse("05/05/2015 12:00:00"));
I want to return a string that contains "24:00:00"
TimeSpan j = DateTime.Parse("06/05/2015 12:00:00").Subtract(DateTime.Parse("05/05/2015 18:00:00"));
I want to return a string that contains "18:00:00"
You can use TimeSpan.TotalHours and String.Format:
string result = string.Format("{0:D2}:{1:D2}:{2:D2}", (int)j.TotalHours, j.Minutes, j.Seconds);
The cast to int is needed to remove the fractional part from the TotalHours.
The D2 ensures that you always get two digits like 00 even if the minute part is 0.
MSDN: The "D" (or decimal) format specifier
Try Something like this,
I have done only for your first condition
DateTime d1 = Convert.ToDateTime( "06/05/2015 12:00:00");
DateTime d2 = Convert.ToDateTime( "04/05/2015 14:00:00");
TimeSpan j = d1 - d2;
string ti = (j.TotalHours + " : " + j.TotalMinutes + " : " + j.TotalSeconds).ToString();
i have done something like:
TimeSpan j = DateTime.Parse("06/05/2015 12:00:00").Subtract(DateTime.Parse("04/05/2015 14:00:00"));
int i = 0;
if(j.Days >= 1)
{
i = j.Days * 24;
i = i + j.Hours;
}
string s = String.Concat(i.ToString(), ":", j.Minutes.ToString(), ":", j.Seconds.ToString());

How To Display Date In Locale For 0 Values?

Ok, so I have a date stored in UK format (dd/mm/yy) which I need to display in the locale of wherever the user might be.
The issue is that this date can be 000000 (00/00/2000); so I can't convert it to DateTime directly, as DateTime doesn't support 0 values for day or month.
I have this so far:
int dateInt = ddmmyy;
var year = (dateInt % 100) + 2000;
var month = (dateInt / 100) % 100;
var day = (dateInt / 100000);
var result = new DateTime(year, month, day); //2014/00/00 at this point, so breaks.
var resultStr = result.ToString(CultureInfo.InvariantCulture);
return resultStr;
What's the correct way to add support for 0 values initially? I've tried changing the 0 to 1 before converting to DateTime, running the conversion and then replacing with a 0 again; but due to culture variants I see no way that this method can support other cultures, which is the purpose of this conversion to begin with.
Any ideas? I'm guessing this is a common issue.
Is this what you need ?
using System;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
int[] savedDates = new int[] { 000000, 010000, 000013 };
foreach (var item in savedDates)
{
DateTime date = ConvertToDate(item);
Console.WriteLine(item.ToString("D6") + " => " + date.ToShortDateString());
}
Console.ReadLine();
}
private static DateTime ConvertToDate(int item)
{
string temp = item.ToString("D6");
int day = int.Parse(temp.Substring(0, 2));
int month = int.Parse(temp.Substring(2, 2));
int year = int.Parse(temp.Substring(4, 2));
if (day == 0)
day = 1;
if (month == 0)
month = 1;
year += 2000;
return new DateTime(year, month, day);
}
}
}
I would not store dates like this as the methodology for doing so is already provided by the .NET framework.
The best way to store dates would be to use Culture.InvariantCulture for string conversion cases and then convert to local culture for display purposes as necessary. DateTime itself is culture-independent so converting between cultures is very easy.

Julian date string to DateTime

I am trying to convert Julian date string to DateTime but none of the solutions on the web seem to be working. I have a Julian date string 13324.
Julian Date: 13324
And I want to get the following DateTime
Date: 20-Nov-2013
Could you please direct me in the right direction. Thanks.
This is the simplest solution I can think of:
string julianDate = "13324";
int jDate = Convert.ToInt32(julianDate);
int day = jDate % 1000;
int year = (jDate - day) / 1000;
var date1 = new DateTime(year, 1, 1);
var result = date1.AddDays(day - 1);
(Note: this is all from memory; verify the syntax, etc.)
Sorry for my bad english
Try this code if the one on top didn't work. It worked for me.
public DateTime ConvertJulianToDatetime(string julianDate)
{
int dateint = int.Parse(julianDate);
DateTime dinicio = new DateTime(1840, 12, 31);
dinicio = dinicio.AddDays((double)dateint);
return dinicio;
}
This code is more reliable I think (can anyone notice):
public static DateTime FromJD(double JD)
{
return DateTime.FromOADate(JD - 2415018.5);
}
For MJD (modified julian day). Math.Floor or Math.Ceiling can be added as needed:
public static DateTime FromMJD(double MJD)
{
return DateTime.FromOADate((MJD - 2415018.5) + 2400000.5);
}
And one example for reverse translation:
public static double ToMJD(DateTime date)
{
return (date.ToOADate() + 2415018.5) -2400000.5;
}
public static double ToJD(DateTime date)
{
return date.ToOADate() + 2415018.5;
}

Convert a string containing monthName to Int of MonthDigit

I have a string which has short month name in it.\
string month = "Jun";
I need to get month in digit from this month name.
Say i do this:
int monthInDigit = getMonth(month);
monthInDigit <-- 6
How can i achieve this. If you cant get my question pleases comment i will explain it proprly.
Thanxx in advance
int monthInDigit = DateTime.ParseExact(month, "MMM", CultureInfo.InvariantCulture).Month;
You can parse it to a DateTime first:
DateTime dt = DateTime.ParseExact("Jun", "MMM", CultureInfo.InvariantCulture);
int month = dt.Month;
if(month < 6)
{
// do something...
}
another way :
string [] arr= {jun, fab,...};
public int getMonth(string month){
for(int i = 0 ; i< arr.length ; i++){
if(string[i].Contains(month) || month.Contains(arr[i]))
return i+1;
}
return -1;// if month is invalid , return -1
}

Categories

Resources