How convert Gregorian date to Persian date? - c#

I want to convert a custom Gregorian date to Persian date in C#.
For example, i have a string with this contents:
string GregorianDate = "Thursday, October 24, 2013";
Now i want to have:
string PersianDate = پنج‌شنبه 2 آبان 1392 ;
or
string PersianDate = 1392/08/02
Thanks

Use the PersianCalendar:
string GregorianDate = "Thursday, October 24, 2013";
DateTime d = DateTime.Parse(GregorianDate);
PersianCalendar pc = new PersianCalendar();
Console.WriteLine(string.Format("{0}/{1}/{2}", pc.GetYear(d), pc.GetMonth(d), pc.GetDayOfMonth(d)));

DateTime date = new DateTime(2013, 10, 24);
var calendar = new PersianCalendar();
var persianDate = new DateTime(calendar.GetYear(date), calendar.GetMonth(date), calendar.GetDayOfMonth(date));
var result = persianDate.ToString("yyyy MMM ddd", CultureInfo.GetCultureInfo("fa-Ir"));

You can use PersianDateTime:
PM> Install-Package PersianDateTime
The Reference: PersianDateTime
You can use string.Split() if you need customization.

Adding up to other answers, You can get the first one by using PersianDateTime:
var gregorianDate = "Thursday, October 24, 2013";
var date = DateTime.Parse(gregorianDate);
var persianDate = new PersianDateTime(date);
var result = persianDate.ToString("dddd d MMMM yyyy");

The fowlling code should work in .net 4+ :
DateTime date=Convert.ToDateTime("2020-07-12T19:30:00.000Z");
string persianDateString = date.ToString("yyyy/MM/dd",new CultureInfo("fa-IR"));
persianDateString value would be:
1399/04/23

In windows 10, using framework 4+:
Console.WriteLine(Convert.ToDateTime("1392/08/02",new CultureInfo("fa-IR")));
or
Console.WriteLine(DateTime.Parse("1392/08/02", new CultureInfo("fa-IR")));

You can convert a DateTime to Iran time using this method:
DateTime timeInIran = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTimeToConvert, "Iran Standard Time" );

Related

convert string to persian date time

I am developing an asp.net web site, I want to convert a string of Persian date to DateTime type and I used below code but I get Gregorian date
System.Globalization.CultureInfo pr = new System.Globalization.CultureInfo("fa-ir");
DateTime dt = DateTime.ParseExact("1396/04/31", "yyyy/MM/dd", pr);
dt is 7/22/2017 but it must be 1396/04/31
I try this code too but have the same problem
PersianCalendar persianDate = new PersianCalendar();
DateTime st = persianDate.ToDateTime(1396, 04, 31, 0, 0, 0, 0);
I use windows 10 and .net 4.5
how can I resolve this problem.
please help me.
you can use PersianCalendar
System.Globalization.CultureInfo pr = new System.Globalization.CultureInfo("fa-ir");
DateTime dt = DateTime.ParseExact("1396/04/31", "yyyy/MM/dd", pr);
PersianCalendar pc = new PersianCalendar();
Console.WriteLine("Today in the Persian Calendar: {0}, {1}/{2}/{3} {4}:{5}:{6}\n",
pc.GetDayOfWeek(dt),
pc.GetYear(dt),
pc.GetMonth(dt),
pc.GetDayOfMonth(dt),
pc.GetHour(dt),
pc.GetMinute(dt),
pc.GetSecond(dt));

How to display date only from datetime type into datetime object

In string array I have date field, which I want to format for date only and bind it to date time object.
string[] strArray = new string[] {
"Mahesh Chand",
"Mike Gold",
"Raj Beniwal",
"Praveen Kumar",
"7/10/1974 7:10:24 AM"
};
DateTime dateFromString = Convert.ToDateTime(strArray[4]);
DateTime dt = DateTime.ParseExact(dateTimeString, "dd/MM/yyyy", null);
Am not getting only date. still am getting date and time.
You can take only the Date without Time from a DateTime object in this way:
DateTime dateFromString = Convert.ToDateTime(strArray[4]);
var onlyDate = dateFromString.Date;
// Display date using short date string.
Console.WriteLine(onlyDate .ToString("d"));
More info on MSDN
Use like this
string[] strArray = new string[] {
"Mahesh Chand",
"Mike Gold",
"Raj Beniwal",
"Praveen Kumar",
"7/10/1974 7:10:24 AM" };
DateTime dateFromString = Convert.ToDateTime(strArray[4]);
string dt= DateTime.ParseExact(dateTimeString, "dd/MM/yyyy", null).ToString("dd/MM/yyyy");
in this way you will get date as string, but if you want only date part as DateTime type then it isn't possible because in DateTime type if you don't specify any time then it will automatically add a default time as 12:00:00 AM(00:00:00) in DateTime
Update
you can use like this for all culture
string dt = DateTime.ParseExact(dateTimeString, "dd/MM/yyyy", CultureInfo.InvariantCulture)
.ToString("dd/MM/yyyy");
or you can use simply like this
string[] strArray = new string[] {
"Mahesh Chand",
"Mike Gold",
"Raj Beniwal",
"Praveen Kumar",
"7/10/1974 7:10:24 AM" };
string dateFromString = Convert.ToDateTime(strArray[4]).ToString("dd/MM/yyyy");

C# String was not recognized as a valid DateTime

Error being thrown when the dateString is the following but worked earlier for a different time, not sure why it isn't working now.
string dateString = "Jul 24, 2015 4:03:51 PM PDT";
string format = "MMM dd, yyyy h:mm:ss tt PDT";
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime time = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine(time);
Edited Code: The error is thrown either of the last two lines, sometimes the first DateTime will execute but not the second. The prompt window just asks for, first, the earliest date and time which is: Jul 24, 2015 6:26:15 AM PDT. And then another prompt for the latest DateTime which is: Jul 24, 2015 4:03:51 PM PDT
string afterpromptvalue = Prompt.ShowDialog("Enter earliest Date and Time", "Unshipped Orders");
string beforepromptvalue = Prompt.ShowDialog("Enter latest Date and Time", "Unshipped Orders");
string format = "MMM dd, yyyy h:mm:ss tt PDT";
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime createdAfter = DateTime.ParseExact(afterpromptvalue, format, provider);
DateTime createdBefore = DateTime.ParseExact(beforepromptvalue, format, provider);
Edited again: I wanted to put the prompt dialog box code, because this may be the issue.
public static class Prompt
{
public static string ShowDialog(string text, string caption)
{
Form prompt = new Form();
prompt.Width = 500;
prompt.Height = 150;
prompt.FormBorderStyle = FormBorderStyle.FixedDialog;
prompt.Text = caption;
prompt.StartPosition = FormStartPosition.CenterScreen;
Label textLabel = new Label() { Left = 50, Top=20, Text=text };
TextBox textBox = new TextBox() { Left = 50, Top=50, Width=400 };
Button confirmation = new Button() { Text = "Ok", Left=350, Width=100, Top=70, DialogResult = DialogResult.OK };
confirmation.Click += (sender, e) => { prompt.Close(); };
prompt.Controls.Add(textBox);
prompt.Controls.Add(confirmation);
prompt.Controls.Add(textLabel);
prompt.AcceptButton = confirmation;
return prompt.ShowDialog() == DialogResult.OK ? textBox.Text : "";
}
}
Your code worked at my machine without any error. Try executing it on some other machine or in different solution. If it works means your solution need to be clean and build. If do not work means you you probably missing required references -
using System;
using System.Globalization;
A common error with date parsing is using dd instead of d. With dd, a value of 24 will pass, but 9 will not; the latter would have to be 09 instead. If you use a single d, however, then 9, 09, and 24 would all be allowed.

Convert string to DateTime Format - wrong format

I really cannot make sense of why this does not want to work. I get an exception:
String was not recognized as a valid DateTime.
I am reading the string date from a file and looks like this 2/27/2014 10:10:55
This method receives the filename and extrapolates the data I need (latitude, longitude, date)
public void ReadCsvFile(string filename)
{
var reader = new StreamReader(File.OpenRead(filename));
gpsDataList = new List<GpsFileClass>();
while(!reader.EndOfStream){
var line = reader.ReadLine();
var values = line.Split(',');
if(values[2].Contains("A")){
values[2] = values[2].Substring(0,values[2].IndexOf("A"));
values[2].Replace("\"", "");
values[2] = values[2].Trim();
}
if(values[2].Contains("P")){
values[2] = values[2].Substring(0, values[2].IndexOf("P"));
values[2].Replace("\"", "");
values[2] = values[2].Trim();
}
gpsDataList.Add(new GpsFileClass(Convert.ToDouble(values[0]), Convert.ToDouble(values[1]), Convert.ToString(values[2])));
}
}
Once the I have the file data in a List<> I want to do some date comparisons and calculations. But first; I try to convert the string data containing date information to datetime like this:
public void SaveFrameGpsCoordinate()
{
int listSize = gpsDataList.Count;
DateTimeFormatInfo dateTimeFormatInfo = new DateTimeFormatInfo();
dateTimeFormatInfo.ShortDatePattern = "dd-MM-yyyy HH:mm:ss";
dateTimeFormatInfo.DateSeparator = "/";
//DateTime tempDateA = DateTime.ParseExact(gpsDataList[0].timeCaptured, "dd/MM/yyyy HH:mm:ss",null);
//DateTime tempDateB = DateTime.ParseExact(gpsDataList[lastRecordData].timeCaptured, "dd/MM/yyyy HH:mm:ss", null);
DateTime tempDateA = Convert.ToDateTime(gpsDataList[0].timeCaptured.Replace("\"", ""), System.Globalization.CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat);
DateTime tempDateB = Convert.ToDateTime(gpsDataList[lastRecordData].timeCaptured.Replace("\"", ""), System.Globalization.CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat);
}
As you can see even ParseExact throws the same exception, I tried it (hence commented it out).
There are a lot solutions for this kind of problem but non seem to work on mine. I get that DateTime by default uses en-US calture. But When I even when I change the culture to "af-ZA" I get the same exception.
Please help.
I don't believe it; The variable that holds the size of the List<> was going out of range (check line 3 of code below) but for some reason it did not throw an "out of range exception".
public void SaveFrameGpsCoordinate()
{
int listSize = gpsDataList.Count - 1;
DateTimeFormatInfo dateTimeFormatInfo = new DateTimeFormatInfo();
dateTimeFormatInfo.ShortDatePattern = "dd-MM-yyyy HH:mm:ss";
dateTimeFormatInfo.DateSeparator = "/";
//DateTime tempDateA = DateTime.ParseExact(gpsDataList[0].timeCaptured, "dd/MM/yyyy HH:mm:ss",null);
//DateTime tempDateB = DateTime.ParseExact(gpsDataList[lastRecordData].timeCaptured, "dd/MM/yyyy HH:mm:ss", null);
DateTime tempDateA = Convert.ToDateTime(gpsDataList[0].timeCaptured.Replace("\"", ""), System.Globalization.CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat);
DateTime tempDateB = Convert.ToDateTime(gpsDataList[lastRecordData].timeCaptured.Replace("\"", ""), System.Globalization.CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat);
}
You can use the ParseExact method
var dateTime = DateTime.ParseExact("2/27/2014 10:10:55",
"M/d/yyyy h:m:s", CultureInfo.InvariantCulture);
'dd' expects a 2 digit date. You probably want to use 'd' instead.
Similarly 'MM' expects a 2 digit month - again you probably want to use 'M' instead.
Source: http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

Convert comma separated string to datetime

The Exchange webservice has a method that takes the DateTime in the format below
appointment.Start = new DateTime(2014, 03, 04, 11, 30, 00);
I have a string which is formed by concatenating various fields to form the date my string is as below:
string date="2014,03,04,11,00,00"
But if i try to to parse my string as the date it gives the error "String was not recognized as a valid DateTime".
DateTime.Parse(date)
You can use DateTime.ParseExact:
string date = "2014,03,04,11,00,00";
DateTime dateTime = DateTime.ParseExact(date, "yyyy,MM,dd,HH,mm,ss", CultureInfo.CurrentCulture);
Try this :
string date = "2014,03,04,11,00,00";
DateTime datDate;
if(DateTime.TryParseExact(date, new string[] { "yyyy,MM,dd,hh,mm,ss" },
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out datDate))
{
Console.WriteLine(datDate);
}

Categories