Based on the following code, when I receive the hijri (Persian) time string in the method and want to convert it to datetime, the format will be returned to the Gregorian format if I want the hijri (Persian) format to be datetime.
public static DateTime Convert_String_To_DateTime(string PersianDate, string Time)
{
PersianCalendar pc = new PersianCalendar();
int year = Convert.ToInt32(PersianDate.Substring(0, PersianDate.IndexOf('/')));
int month = Convert.ToInt32(PersianDate.Substring(PersianDate.IndexOf('/') + 1, 2));
int day = Convert.ToInt32(PersianDate.Substring(PersianDate.IndexOf('/') + 4, 2));
int hour = Convert.ToInt32(Time.Substring(0, Time.IndexOf(':')));
int min = Convert.ToInt32(Time.Substring(Time.IndexOf(':') + 1));
DateTime ConvertedDate = new DateTime(year, month, day, hour, min, 0, pc);
return ConvertedDate;
}
I am not 100% sure what you want to accomplish but if you want to change the output of your date and time you can use
DateTime dt = DateTime.Now;
string mydate = dt.ToString("dd-MM-yyyy hh:mm:ss");
dd - day
MM - Month short ex. for August you gonna get 08 if you want just 8 use single M and MMM for 3 letters and MMMM for a full month like August
yyyy - Year same rule applies to year as well
hh-Hour
mm-minute
ss secont
you have as well tt that will show you AM/PM
you use from PersianCalendar library and you should solve your problem with this function in that library
Datetime miladiconvert= PersianDateTime.Parse(Yourvariable).ToDateTime();
but you should pass currect format in this parsing so you should this funcation i wrote and use it
public string convertdate(string date)
{
string[] st = new string[3];
st = date.Split('/');
if (int.Parse(st[0]) < 10)//year
{
st[0] = "0" + st[0];
}
if (int.Parse(st[1]) < 10 && st[1].Length == 1)//month
{
st[1] = "0" + st[1];
}
if (int.Parse(st[2]) < 10 && st[2].Length == 1)//day
{
st[2] = "0" + st[2];
}
date = st[0] + "/" + st[1] + "/" + st[2];
return date;
}
Finally if you want add hour and minutes you can use from add
miladiconvert= miladiconvert.AddHours(your Hours)
miladiconvert=miladiconvert.AddMinutes(your Minutes)
Related
I need help in C# getting month names from current month, meaning user inputs a month(name) and will return the list of months from the starting month until the current month.
Example; user inputs "August" and current month is "December" so it should return "August, September, October, November, December".
I've done a few steps but still can't get to it.
1st try:
string pattern = ("MMMM/yyyy");
Console.WriteLine("Enter Month: MMMM/yyyy");
DateTime inpMonth = DateTime.ParseExact(Console.ReadLine(),pattern,System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);
string last = inpMonth.ToString("MMMM/yyyy");
DateTime date = DateTime.Now;
string curr = date.ToString("MMMM/yyyy");
2nd Try(new step):
//First Date
DateTime 1Date = new DateTime(2020, 12, 01);
//Second Date
DateTime 2Date =new DateTime(2019, 01, 01);
int month1 = (2Date.Month - 1Date.Month);
int month2 = (2Date.Year - 1Date.Year) * 12;
int months = month1 + month2;
string mon = months.DateTime.ToString("MMMM"); //trying to convert the month number to month name
Both try seems to not get any close result..
The following code will output to the result you requested:
var start = "August";
var today = DateTime.Today;
var date = new DateTime(today.Year, DateTime.ParseExact(start, "MMMM", CultureInfo.CurrentCulture).Month, 1);
while (date < today)
{
Console.WriteLine($"{date:MMMM}");
date = date.AddMonths(1);
}
I have a Google API that takes date and time and sets up a event in customers calendar and the problem is I am using date time to add hours to the event when I boot time for 12pm noon For whatever reason, it will be listed in my Google Calendar for the day after at 12am.
Here is the code that sets up the date and the time:
// dd is a drop down for hours 1 to 12 Central Time Zone
int iHour = Convert.ToInt32(dd.SelectedItem.Text);
// and this is the minutes values of 30 or 45
int iMinute = Convert.ToInt32(ddMinute.SelectedItem.Text);
var date = "Nov 19, 2017";
DateTime dt = new DateTime();
dt = Convert.ToDateTime(date);
// If its PM set 12 hours more to it because its a 24 hours clock
if (ddAptAmPm.SelectedValue == "PM")
iHour += 12;
dt = dt.AddHours(iHour);
dt = dt.AddMinutes(iMinute);
var startDate = dt;
var endDate = dt;
string sNotes = "TestingA PI";
string sTitle = "Testas" + " with: " + "ASP.NEt" + " " + "Last Name here";
int length = Convert.ToInt32("30");
endDate = endDate.AddMinutes(length);
var google = new GoogleCalendar();
int value = google.CreateCalendarEvent("email", startDate, endDate, sNotes, sTitle);
Can any one see where did I do this wrong
if (ddAptAmPm.SelectedValue == "PM") // If its PM set 12 hours more to it because its a 24 hours clock
iHour += 12;
should be:
if (ddAptAmPm.SelectedValue == "PM" && iHour < 12) // If its 1-11 PM set 12 hours more to it because its a 24 hours clock
iHour += 12;
else if (ddAptAmPm.SelectedValue == "AM" && iHour == 12)
iHour = 0;
Since 12 + 12 is 24, and today plus 24 hours is the next day.
Another way to write it:
if (iHour == 12) // 12 is **before** 1
iHour = 0;
if (ddAptAmPm.SelectedValue == "PM") // If its PM set 12 hours more to it because its a 24 hours clock
iHour += 12;
Another way you could do it is to construct a date string in a specific format (including the AM or PM designation), and then use DateTime.ParseExact to create your startDate. This way you don't have to do all the conversion from string to int, then add 12 hours if PM was specified, etc.
For example, this code would replace everything you currently have up to and including the startDate assignment:
// This assumes that ddAptAmPm.SelectedValue will be "AM" or "PM"
var dateString = string.Format("Nov 19, 2017 {0}:{1} {2}", dd.SelectedItem.Text,
ddMinute.SelectedItem.Text, ddAptAmPm.SelectedValue);
// In a format string, tt is a placeholder for AM/PM
var startDate = DateTime.ParseExact(dateString, "MMM dd, yyyy h:m tt",
CultureInfo.InvariantCulture);
You can read more about Date and Time Format Strings here.
I want to calculate year and month in my web application.
In my code, I have year 201604. I want to subtract the month by 3, So it should be 201601. I got this part work but now if I want to subtract another 3 monyths from 201601 again, the result should be 201511. I am not sure how to do this part. Help will be appreciated
Code
decimal str = "201604";
decimal year= (decimal) Calculations.ParseStringToDecimal(str.SubString(0,4), 0);
decimal month = (decimal) Calculations.ParseStringToDecimal(str.SubString(4,2), 0);
newMonth = month - 3;
string newDate = year + month
//Result: 201601.
//I want to subtract 201601 again, then the result should be 201511.
When working with dates use DateTime class which has been specially designed for this purpose:
String str = "201604";
DateTime date = DateTime.ParseExact(str, "yyyyMM", CultureInfo.InvariantCulture)
.AddMonths(-3);
// 201601
String newDate = date.ToString("yyyyMM");
DateTime threemonthprevDate = DateTime.ParseExact(str,"yyyyMM",CultureInfo.InvariantCulture).AddMonths(-3);
DateTime sixmonthprevDate = threemonthprevDate.AddMonths(-3));
Use ParseExact method instead.
string str = "201604";
DateTime dateTime = new DateTime(int.Parse(str.Substring(0, 4)), int.Parse(str.Substring(4, 2)), 1);
dateTime = dateTime.AddMonths(-3);
string resultString = dateTime.ToString("yyyyMM");
string str = "201604";
decimal year= (decimal) Calculations.ParseStringToDecimal(str.SubString(0,4), 0);
decimal month = (decimal) Calculations.ParseStringToDecimal(str.SubString(4,2), 0);
DateTime dateObj = new Date(year, month, 1);
dateObj.AddMonths(-3);
//201601
string newDate1 = dateObj.ToString("yyyyMM");
dateObj.AddMonths(-3);
//201511
string newDate1 = dateObj.ToString("yyyyMM");
Assuming I can not change service that returns data, I am left with
var date = "20140231";
var scope = DateTime.ParseExact(date, "yyyyMMdd", CultureInfo.CurrentCulture);
Clearly "20140231" is lazy way of saying end of February. What is the cleanest way to get last date of February with input of "20140231"?
There is 1 constraint - this should work with .net 2.0.
string date = "20140231";
DateTime result;
int year = Convert.ToInt32(date.Substring(0, 4));
int month = Convert.ToInt32(date.Substring(4, 2));
int day = Convert.ToInt32(date.Substring(6, 2));
result = new DateTime(year, month, Math.Min(DateTime.DaysInMonth(year, month), day));
February can have only 28 or 29 days depends on current year is a leap year or not.
It can't have 30 or 31 days in any year. That's why you can't parse your 20140231 string successfully.
You can clearly get the last day of February like;
DateTime lastDayOfFebruary = (new DateTime(2014, 2, 1)).AddMonths(1).AddDays(-1);
If your service always get year as a first 4 character, you can use .Substring() to get year and pass DateTime constructor as a year.
var date = "20140231";
string year = date.Substring(0, 4);
DateTime lastDayOfFebruary = (new DateTime(int.Parse(year), 2, 1)).AddMonths(1).AddDays(-1);
You could create a while, cut the date in pieces, and keep subtracting one from the day part until it is a valid date. This should really be fixed on the entry side though.
Try this:
var date = "20140231";
DateTime scope;
bool dateValid = DateTime.TryParseExact(date, "yyyyMMdd", CultureInfo.CurrentCulture, DateTimeStyles.None, out scope);
while (!dateValid)
{
string yearMonth = date.Substring(0, 4);
int day = Convert.ToInt32(date.Substring(6, 2));
if (day > 1)
{
day--;
}
else
{
break;
}
date = yearMonth + day.ToString().PadLeft(2, '0');
dateValid = DateTime.TryParseExact(date, "yyyyMMdd", CultureInfo.CurrentCulture, DateTimeStyles.None, out scope);
}
This is what i could write?
string text = string.Format("{0:d/MM/yy}", DateTime.Now.Date);
text = text.Replace("-", "");
char[] cString = text.ToCharArray();
string year = text.Substring(text.Length - 2);
string month = cString[2].ToString() + cString[3].ToString();
string day = cString[0].ToString() + cString[1].ToString();
Please help me find the mistake as it is not getting displayed correctly on my Win Form Application. It is showing 01 05 13 as 10 __ 13.
DateTime today = DateTime.Now;
int year = today.Year;
int month = today.Month
int day = today.Day;
You can do that like this:
var date = DateTime.Now.Date;
var parts = date.ToString("d MM yy").Split(" "); // dd MM yy for 2-digit day
var year = parts[2];
var month = parts[1];
var day = parts[0];
But this seems even easier:
var date = DateTime.Now.Date;
var year = date.ToString("yy");
var month = date.ToString("MM");
var day = date.ToString("d"); // dd for 2-digit day
Couldn't you do:
DateTime currDate = DateTime.Now;
string year = currDate.ToString("yy");
string month = currDate.ToString("MM");
string day currDate.ToString("d");
or just
string date = DateTime.Now.ToString("d MM yy");