Get Indian Time only in HH:MM hours & mins - c#

I am using following code to get local(IST) time. But I don't want to display Date & seconds and also want it in 12hr (AM / PM) format. Please help.
With following code I am getting time like this
9/13/2016 11:38:17 AM
I want it like this
11:38 AM
partial class Default3 : System.Web.UI.Page
{
DateTime UTCTime = System.DateTime.UtcNow;
DateTime IndianTime = UTCTime.AddHours(5.5);
private void Default3_Load(object sender, EventArgs e)
{
myTime.Text = IndianTime;
}
public Default3()
{
Load += Default3_Load;
}
}

You can display your datetime like this
DateTime dt = DateTime.Parse("6/22/2009 07:00:00 AM");
dt.ToString("HH:mm"); // 07:00 // 24 hour clock // hour is always 2 digits
dt.ToString("hh:mm tt"); // 07:00 AM // 12 hour clock // hour is always 2 digits
dt.ToString("H:mm"); // 7:00 // 24 hour clock
dt.ToString("h:mm tt"); // 7:00 AM // 12 hour clock

To get time in India in request format, you can use this
var zone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
var timeInIndia = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, zone);
var timeInIndiaAsString = timeInIndia.ToString("hh:mm tt", CultureInfo.InvariantCulture);

Try:
partial class Default3 : System.Web.UI.Page
{
UTCTime = System.DateTime.UtcNow;
IndianTime = UTCTime.AddHours(5.5).Date;
private void Default3_Load(object sender, EventArgs e)
{
myTime.Text = IndianTime.ToShortDateString();
}
public Default3()
{
Load += Default3_Load;
}
}
If that doesn't work, try something like:
DateTime UTCTime = System.DateTime.UtcNow;
DateTime IndianTime = UTCTime.AddHours(5.5).Date;
partial class Default3 : System.Web.UI.Page
{
private void Default3_Load(object sender, EventArgs e)
{
UTCTime = System.DateTime.UtcNow;
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0);
IndianTime = epoch.AddDays(Math.Floor(IndianTime.Subtract(epoch).TotalDays));
myTime.Text = IndianTime.ToShortDateString();
}
public Default3()
{
Load += Default3_Load;
}
}
The second example is overkill in terms of formatting, but useful if you need to compare a DateTime to something stored as a Date (as in a database). The result of IndianTime in the second example will evaluate to "true" if you need to "remove the time for a DateTime."
Remember - a DateTime is nothing but an integer - it's up to you to format it however you want.

Related

DateTimePicker Type

I have some coding part for get exactly date by counting days.
void datecheck()
{
int result = 0;
if (int.TryParse(textBox1.Text, out result))// Input format Error
{
if (textBox1.Text.Trim() == string.Empty)
{
MessageBox.Show("Please enter number of days to count..!");
return; // return because we don't want to run normal code of buton click
}
else
{
string m = textBox1.Text;
int number = 0;
number = int.Parse(m);
int X = Convert.ToInt32(m.ToString());
System.DateTime today = dateTimePicker1.Value.Date;
System.TimeSpan duration = new TimeSpan(X, 0, 0, 0);
System.DateTime answer = today.Add(duration);
duetoback.Text = answer.ToShortDateString();
}
}
else
{
MessageBox.Show("Error Format..!");
}
}
So this coding give result as ("DD/MM/YYYY")
but I need the result with format as follows
DateTime.Now.ToString("dddd, dd MMMM yyyy")
Help me to debug this and Please give me some comment about this coding part which its better or not
If I understand the question correctly, you are asking for:
I need the result with format as follows
DateTime.Now.ToString("dddd, dd MMMM yyyy")
Then you can try this approach, just pass in any DateTime variable into $"{HERE:FORMAT}";
var now = DateTime.Now;
Console.WriteLine(now); // 2020-06-06 16:20:02
var formattedNow = $"{now:dddd, dd MMMM yyyy}";
Console.WriteLine(formattedNow); // Saturday, 06 june 2020

Double to DateTime

I try to do little program, to convert DateTime to Double and from double to DateTime.
I used DateTimePicker in C#, to make my users choose date and time to convert, and it works great, but I have little problem with converting double value to DateTime.
When I have double value, I can easilly convert it to Date by using something like this var dt = DateTime.FromOADate(doubleDate); and var date = dt.Date; but I have no idea, how to convert this double value to time.
This is my code:
private void button2_Click(object sender, EventArgs e)
{
var doubleDate = Convert.ToDouble(textBox1.Text);
var dt = DateTime.FromOADate(doubleDate);
var date = dt.Date;
this.dateDateTime.Value = date;
}
Example value: 42722,7819696875 or 42710,5736342593
You need to set the format on the DateTimePicker, Try the following:
var d = 42722.7465005671d; // 12/18/2016 5:54:57 PM
var dateTime = DateTime.FromOADate(d);
this.dateDateTime.Value = date;
this.dateDateTime.Format = DateTimePickerFormat.Time;

How to get the day value out of a textbox in C#?

For example, if the textbox contains 11/11/2016 OR 01/05/2016
How to get the day value only? example. 11 OR 01
One way is to parse the string in the TextBox to DateTime using an exact format. Then using the DateTime object, you can extract the Day Property:
DateTime date;
bool success = DateTime.TryParseExact(textBoxDate.Text, "dd/MM/yyyy",
CultureInfo.CurrentCulture,
DateTimeStyles.AssumeLocal, out date);
int day;
if(success)
{
day = date.Day; // 1
// or string stringDay = date.ToString("dd"); to get 01
}
else
{
// handle error
}
Another way that I don't prefer (Not 100% safe input validation) is to use String.Split like this:
string strDay = textBoxDate.Text.Split('/').FirstOrDefault();
int day;
if(Int32.TryParse(strDay, out day))
{
// success
}
else
{
// Handle Error
}
string myString = textbox1.text;
DateTime day = DateTime.ParseExact(myString, "dd/MM/yyyy", CultureInfo.InvariantCulture);
int day = birthday.Day;

DateTime formatting error?

I want to compare dates. One date will be hard coded other will be picked from system.
My code is giving formatting error in this line:
string iStringdate = "05-05-2015";
DateTime oDate = DateTime.ParseExact(iStringdate, "dd-mm-yyyy", null);
Complete code:
private void button1_Click(object sender, EventArgs e)
{
string iStringdate = "05-05-2015";
DateTime oDate = DateTime.ParseExact(iStringdate, "dd-mm-yyyy", null);
//MessageBox.Show(oDate.ToString());
string iStringtime = "10:12 pm";
DateTime oTime = DateTime.ParseExact(iStringtime, "HH:mm tt", null);
//MessageBox.Show(oTime.ToString());
DateTime time = DateTime.Now;
DateTime date = DateTime.Today;
if (oDate < date)
{
Console.WriteLine("successfull");
}
else {
Console.WriteLine("fail");
}
}
Also how can I just get the system date and not the system time along with it?
Where am I wrong?
"mm" stands for minutes while "MM" means months.
DateTime.ParseExact(iStringdate, "dd-MM-yyyy", null);
Click here for a complete list of date formatting options.
And DateTime.Now returns the date and time, while DateTime.Today returns the current date and 00:00:00 as time.

How do I calculate the number of days using MonthCalendar in C#?

I have added the calendar form and it won't let me select 2 dates. It assigns every click to the start date so when I try this it always tells me the difference is 1 and the start date is always changed to whatever my next click is?
Is it possible to have it default to today's date for the start date and then have every other click determine the end date? When I tried to assign today's date within the datechanged event handler it wouldn't let me change the month because it kept focusing on the startdate?
private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
{
numDays = Convert.ToInt32((monthCalendar1.SelectionEnd - monthCalendar1.SelectionStart).TotalDays);
MessageBox.Show("num " + numDays);
}
// Sets the Month Calenders Min & Max to days in current month.
DateTime dt = DateTime.Today;
DateTime firstDay = new DateTime(dt.Year, dt.Month, 1, 0, 0, 0);
DateTime lastDay = new DateTime(dt.Year, dt.Month, DateTime.DaysInMonth(dt.Year, dt.Month));
dateMonthCalender.MinDate = firstDay;
dateMonthCalender.MaxDate = lastDay;
The above will set min and max to days in current month
If you want to set the min to today
dateMonthCalender.MinDate = DateTime.Now;
Hope that helps..
Okay so declare two ints and assign one to selected day and the other to today and create yourself a method
int selectedDay;
int todayValue;
DateTime firstDay = new DateTime(dt.Year, dt.Month, 1, 0, 0, 0);
DateTime today = DateTime.Today;
string todayShort = today.ToShortDateString();
string thisDay = todayShort.Substring(0, 2);
todayValue = Convert.ToInt32(thisDay);
private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
{
// Shorten date format to day and assign it.
string dMC = dateMonthCalender.SelectionRange.Start.ToShortDateString();
string takeDMCDay = dMC.Substring(0, 2);
selectedDay = Convert.ToInt32(takeDay);
}

Categories