how to get AM/PM from datetime? c# - c#

I have a date like this:
equipBooking.BookedFromDteTme.Date = `{12/5/2013 12:00:00 AM}`
and I want to apply time like this, but I do not know how to get AM and PM from the end.
dtStartTimeHour.SelectedItem = equipBooking.BookedFromDteTme.TimeOfDay.Hours;
dtStartTimeMin.SelectedItem = equipBooking.BookedFromDteTme.TimeOfDay.Minutes;
**dtStartTimeAMPM.SelectedItem = equipBooking.BookedFromDteTme.???????.;**
Please help me.
I have tried something like this:
var startDatestr = equipBooking.BookedFromDteTme.TimeFrom.Split(new string[] { ":", ":",":",":" }, StringSplitOptions.RemoveEmptyEntries);
AM/PM = startDatestr[3]

If you just want the string you can do:
equipBooking.BookedFromDteTme.ToString("tt");
Or for a boolean result use:
bool isPM = (equipBooking.BookedFromDteTme.Hour >= 12);
BTW, you don't need to call TimeOfDay - you can get the Hour and Minute property directly from the DateTime:
dtStartTimeHour.SelectedItem = equipBooking.BookedFromDteTme.Hour;
dtStartTimeMin.SelectedItem = equipBooking.BookedFromDteTme.Minute;
dtStartTimeAMPM.SelectedItem = equipBooking.BookedFromDteTme.ToString("tt");

TimeSpan does not store time-of-day, but rather the length of any interval of time. It has no notion of AM/PM.
TimeOfDay returns the amount of time since midnight.
If Hours is more than or equal to 12, that will be PM.

try using dateTime.ToString("tt");

Related

Alternative Datetime.Now with only time (21:10)

I was wondering if there's a method or anything which will provide me the current systemtime without the date. I need to use this in a formula and if i want to use the DateTime.NowI have to String.Split this string before I can convert this to a Int.
example: It's 5pm
I want:
'17:00', '5:00', '1700', '500'
Not:
'17:00 PM 29/03/2013'
A DateTime holds the hour and minutes as properties.
var now = DateTime.Now;
var minutes = now.Minute;
var hours = now.Hour;
why cannot you simply format your date i.e.
string CurrentTime = DateTime.Now.ToString("hh:mm:ttt");
I guess what you are looking for is how to format a DateTime correctly.
Look here or here for how this is done.
You could use TimeOfDay. Basically it extracts the time part of a DateTime:
DateTime now = DateTime.Now;
TimeSpan time = now.TimeOfDay;
Do note that unlike the DateTime.Date property, DateTime.TimeOfDay returns a Timespan, not a DateTime.
for "1700" :
date.ToString('HHMM');
Use the DateTime.ToString method:
DateTime dt = DateTime.Now; // Suppose it is currently 5pm
dt.ToString("HH:mm"); // 17:00
dt.ToString("h:mm"); // 5:00
dt.ToString("HHmm"); // 1700
dt.ToString("hmm"); // 500

How to get yesterday's date in C#

I want to retrieve yesterday's date in my ASP.NET web application using C#.
I've tried searching for a solution but have not had much success. The code I'm using just outputs today's date:
string yr = DateTime.Today.Year.ToString();
string mn = DateTime.Today.Month.ToString();
string dt = DateTime.Today.Day.ToString();
date = string.Format("{0}-{1}-{2}", yr, mn, dt);
How can I get yesterday's date?
Use DateTime.AddDays() method with value of -1
var yesterday = DateTime.Today.AddDays(-1);
That will give you : {6/28/2012 12:00:00 AM}
You can also use
DateTime.Now.AddDays(-1)
That will give you previous date with the current time e.g. {6/28/2012 10:30:32 AM}
The code you posted is wrong.
You shouldn't make multiple calls to DateTime.Today. If you happen to run that code just as the date changes you could get completely wrong results. For example if you ran it on December 31st 2011 you might get "2011-1-1".
Use a single call to DateTime.Today then use ToString with an appropriate format string to format the date as you desire.
string result = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd");
You don't need to call DateTime.Today multiple times, just use it single time and format the date object in your desire format.. like that
string result = DateTime.Now.Date.AddDays(-1).ToString("yyyy-MM-dd");
OR
string result = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd");
You will get yesterday date by this following code snippet.
DateTime dtYesterday = DateTime.Now.Date.AddDays(-1);
var yesterday = DateTime.Now.AddDays(-1);
Something like this should work
var yesterday = DateTime.Now.Date.AddDays(-1);
DateTime.Now gives you the current date and time.
If your looking to remove the the time element then adding .Date constrains it to the date only ie time is 00:00:00.
Finally .AddDays(-1) removes 1 day to give you yesterday.
string result = DateTime.Now.Date.AddDays(-1).ToString("yyyy-MM-dd");
DateTime dateTime = DateTime.Now ;
string today = dateTime.DayOfWeek.ToString();
string yesterday = dateTime.AddDays(-1).DayOfWeek.ToString(); //Fetch day i.e. Mon, Tues
string result = dateTime.AddDays(-1).ToString("yyyy-MM-dd");
The above snippet will work. It is also advisable to make single instance of DateTime.Now;
DateTime.Today as it implies is todays date and you need to get the Date a day before so you subtract one day using AddDays(-1);
There are sufficient options available in DateTime to get the formatting like ToShortDateString depending on your culture and you have no need to concatenate them individually.
Also you can have a desirable format in the .ToString() version of the DateTime instance

How to set current time to a value

I was just wondering if there is a way to get the current time and set it into a value.
If its 12:06 AM.. I want to get that time and set it into currentTime.
Example
float currentTime = 0;
currentTime = 12.06;
As others have mentioned, the DateTime class would be ideal for this, and to work out the difference between 2 date/times:
DateTime end = DateTime.Now;
DateTime start = new DateTime(2011, 12, 5, 12, 6,0);
double hours = (end - start).TotalHours;
The subtraction of DateTime objects results in a TimeSpan object that you can use to see the hours/minutes etc.
try DateTime class
DateTime dt = DateTime.Now;
Is this what you're looking for?
DateTime currentTime;
currentTime = DateTime.Now;
Don't use floats or strings. You can do all kinds of cool things using DateTime.
Here's how you'd get the hours that someone worked:
var clockIn = new DateTime(2011,12,4,9,0,0); // December 4th, 9 AM
var clockOut = new DateTime(2011,12,4,17,0,0); // December 4th, 5 PM
var duration = clockOut - clockIn; // TimeSpan
Console.Write(duration.TotalHours); // 8
A few people have mentioned how, but as a 'better' recommendation you should use
DateTime currentTime = DateTime.UtcNow
Otherwise you have issues when the clocks go back, if your timing code is run on those days. (plus it is far easier to alter the UTC time to local time than it is to convert a '1am' to UTC (as there will be two of them when the clocks go back)
Well if you really what it as a float then try:
var currentDate = DateTime.Now;
float currentTime = float.Parse((currentDate.Hour > 12 ? currentDate.Hour -12 :
currentDate.Hour) + "." + currentDate.Minute);
I wouldn't recommend comparing dates or time with floats. A better options would be to use timespans.
You should be using a Timespan instance for time related values, you can use the flexibility to get the required values like
TimeSpan ts = DateTime.Now.TimeOfDay;
ts.ToString("hh:mm") // this could be what you are looking for
You could then use ts.TotalHours which would give you fractional hours (as a double) else you could construct a string specifically using ts.Hours ..ts.Minutes play around and it could be prove useful.
Try the following:
DateTime StartTime=StartTime value;
DateTime CurrentTime=DateTime.Now;
TimeSpan dt = CurrentTime.Subtract(StartTime);
In dt you will get a working time period.
If you want to have the difference between two times, then do this:
DateTime dateOne = DateTime.Parse(enteredTime);
DateTime dateTwo = DateTime.Now;
TimeSpan difference = dateOne - dateTwo;

C# Is it possible to convert DateTime format to integer or float?

I'm having some trouble here.
Did some research on Google but I can't seem to find what I'm looking for.
I'm trying to ask for two inputs (datetimes) in hh:mm format, subtract one for the other then return the result of that value in minutes.
The problem is that I want to return that value as an integer and I can't seem to find the right way to do it.
In C/C++ I wouldn't have this kind of issues...
Anyways, here's a snippet of what I'm talking about.
private int DuraçaoTreino(DateTime dtInicioTreino, DateTime dtFimTreino, int dtDuraçao)
{
Console.WriteLine("Introduza a hora de inicio (hh:mm): ");
dtInicioTreino = Convert.ToDateTime(Console.Read());
Console.WriteLine("Introduza a hora de fim (hh:mm): ");
dtFimTreino = Convert.ToDateTime(Console.Read());
dtDuraçao = (dtFimTreino - dtInicioTreino); // duração da sessão de treino
dtDuraçao = Convert.ToDecimal(Console.Read());
return dtDuraçao;
}
And that's pretty much it... I'm new to C# so if you see anything wrong please be kind.
Thanks in advance.
What you're talking about is a TimeSpan:
DateTime dtBegin = new DateTime(2011,5,1,22,0,0) ; // 10pm 1 May 2011
DateTime dtEnd = new DateTime(2011,5,1,23,0,0) ; // 11pm 1 May 2011
TimeSpan tmElapsed = dtEnd - dtBegin ; // tmElapsed is a TimeSpan with a value of 60 minutes
To return the minutes, do something like:
int elapsedTimeInMinutes = (int) Math.Round( tmElapsed.TotalMinutes , 0 ,MidpointRounding.ToEven ) ;
var timeInMinutes = new DateTime(2011, 12, 25).Subtract(new DateTime(2010, 1, 1)).TotalMinutes;
Instead of creating the DateTime objects using the constructor I used, you can use DateTime.Parse, or better still DateTime.ParseExact to convert the strings to date times. (I know I am only using date parts here but you choose only to use time parts if you wish)
Convert DateTime objects to TimeSpan's, substract and call TimeSpan.TotalMinutes (or smth like that - dont' have VS at hand):
DateTime dt1, dt2;
// Assign some dates, then:
TimeSpan ts = dt2 - dt1;
double minutes = ts.TotalMinutes;

Replace date in a DateTime with another date

How do you change the day part of a DateTime structure?
I have a DateTime with the value of 3/31/2009 8:00:00 AM and would like to change it to any other date but the time should be same. I don't need a solution to add day(s), I need to replace it with any arbitrary date.
How do I achieve this?
To construct a DateTime from two other DateTimes, one of which contains the date and one of which contains the time, you can use:
DateTime result = date.Date + time.TimeOfDay;
day = 1
month = 4
year = 2009
Date2 = new DateTime(day,month,year,Date1.Hours,Date1.Minute,Date1.Seconds)
s = s.AddDays(1)
You should use DateTime.AddDays method. Like this:
DateTime s2 = s.AddDays( 1 );

Categories

Resources