本文整理汇总了C#中System.DateTime.Add方法的典型用法代码示例。如果您正苦于以下问题:C# DateTime.Add方法的具体用法?C# DateTime.Add怎么用?C# DateTime.Add使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.DateTime
的用法示例。
在下文中一共展示了DateTime.Add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GenerateNextEntrance
public void GenerateNextEntrance(DateTime currentTime)
{
TimeSpan timeBetweenTwoEnter = TimeSpan.FromMinutes(Math.Round(RandomEngine.GetExpo(12))); // Const
if (World.Instance != null)
{
if (World.Instance.MnuChkFastEntrance.IsChecked)
{
while (timeBetweenTwoEnter.TotalMinutes > 30)
{
timeBetweenTwoEnter = TimeSpan.FromMinutes(Math.Round(RandomEngine.GetExpo(12)));
}
}
}
DateTime entraneTime = currentTime.Add(timeBetweenTwoEnter);
if (entraneTime > EndTime)
{
//NO More Entrance!
}
else
{
EventList.Add(new FutureEvent(Events.Arrival, currentTime.Add(timeBetweenTwoEnter)));
}
}
示例2: IsRoomAvailable
public bool IsRoomAvailable(Guid eventId, Room room, DateTime start, DateTime end)
{
if (room.EndTime < room.StartTime)
{
if (room.EndTime < room.StartTime)
{
if ((new TimeSpan(start.Hour, start.Minute, 0)).Ticks < (new TimeSpan(room.StartTime.Hours, room.StartTime.Minutes, room.StartTime.Seconds)).Ticks)
start = start.AddDays(1);
if ((new TimeSpan(end.Hour, end.Minute, 0)).Ticks < (new TimeSpan(room.StartTime.Hours, room.StartTime.Minutes, room.StartTime.Seconds)).Ticks)
end = end.AddDays(1);
}
}
var isEventRoomBooked = BookedRooms.Where(x => !x.EventRoom.Event.IsDeleted && x.EventRoom.EventID != eventId && x.EventRoom.RoomID == room.ID).Any(x => IsDateBetweenAnotherTwo(start, end, x.StartTimeEx)
|| IsDateBetweenAnotherTwo(x.StartTimeEx, x.EndTimeEx, start) || IsDateBetweenAnotherTwo(x.StartTimeEx, x.EndTimeEx, end.Add(new TimeSpan(0, 0, -1, 0)))
|| IsDateBetweenAnotherTwo(start, end, x.EndTimeEx.Add(new TimeSpan(0, 0, -1, 0))));
var isEventCateringBooked = BookedCaterings.Where(x => !x.EventCatering.Event.IsDeleted && x.EventCatering.EventID != eventId && x.EventCatering.RoomID == room.ID).Any(x => IsDateBetweenAnotherTwo(start, end, x.StartTimeEx)
|| IsDateBetweenAnotherTwo(x.StartTimeEx, x.EndTimeEx, start) || IsDateBetweenAnotherTwo(x.StartTimeEx, x.EndTimeEx, end.Add(new TimeSpan(0, 0, -1, 0)))
|| IsDateBetweenAnotherTwo(start, end, x.EndTimeEx.Add(new TimeSpan(0, 0, -1, 0))));
var isRoomBooked = isEventRoomBooked || isEventCateringBooked;
return !isRoomBooked;
}
示例3: StartPing
internal override async Task StartPing()
{
_lastActivity = DateTime.Now.Add(_pingTimeout);
_pingInterval = TimeSpan.FromMilliseconds(Math.Max(500, _pingTimeout.TotalMilliseconds / 2));
while (_connection.IsConnected)
{
await Task.Delay(_pingInterval).ConfigureAwait(false);
try
{
var now = DateTime.Now;
if (_lastActivity.Add(_pingTimeout) < now)
{
_connection.Close(WebSocketCloseReasons.GoingAway);
}
else if (_lastActivity.Add(_pingInterval) < now)
{
_connection.WriteInternal(_pingBuffer, 0, true, false, WebSocketFrameOption.Ping, WebSocketExtensionFlags.None);
}
}
catch(Exception ex)
{
DebugLog.Fail("BandwidthSavingPing.StartPing", ex);
_connection.Close(WebSocketCloseReasons.ProtocolError);
}
}
}
示例4: FillGuide
protected override async Task FillGuide(DateTime date) {
Queue<TimeSpan> newsQueue=new Queue<TimeSpan>(5); TimeSpan previousTime=new TimeSpan(-1);
foreach (Match match in broadcastRx.Matches(
await client.DownloadStringTaskAsync(string.Concat("http://echo.msk.ru/schedule/", date.ToString(@"yyyy\-MM\-dd"), ".html")))) {
GroupCollection groups=match.Groups;
string title=htmlRx.Replace(groups["title"].Success ? groups["title"].Value:groups["notice"].Value, string.Empty);
Match newsMatch=newsRx.Match(title);
if (newsMatch.Success) {
newsQueue.Clear();
title=newsMatch.Groups["caption"].Value;
foreach (Capture cap in newsMatch.Groups["time"].Captures)
newsQueue.Enqueue(TimeSpan.Parse(cap.Value.Substring(0, 5))); // Substring lai atstātu tikai laiku.
}
var sb=new StringBuilder();
if (groups["title"].Success && groups["notice"].Value.Length != 0) sb.Append(groups["notice"].Value);
AddPeople("guests", "Гость ", "Гости ", sb, groups);
AddPeople("presenters", "Ведущий ", "Ведущие ", sb, groups);
TimeSpan time=TimeSpan.Parse(groups["time"].Value);
while (newsQueue.Count != 0 && time >= newsQueue.Peek()) {
TimeSpan newsTime=newsQueue.Dequeue();
if (time != newsTime) AddBroadcast(date.Add(newsTime), "Новости", null, null);
}
if (time == previousTime) continue;
AddBroadcast(date.Add(time),
quoteRx.Replace(title.Replace(""", "\""), "«$1»"),
sb.Length != 0 ? sb.ToString():null,
groups["url"].Success ? groups["url"].Value:null);
previousTime=time;
}
}
示例5: GrilleHoraire
//Id des blocs en mémoires
public GrilleHoraire(Graphics grfx, Loader loader, DateTime date)
{
gfx = grfx;
this.loader = loader;
//DateTime renvoyer par la fonction getweekrange()
laDate = date;
//DateTime et une addition de timespan
DateTime lundi = laDate;
DateTime mardi = laDate.Add(new TimeSpan(24, 0, 0));
DateTime mercredi = laDate.Add(new TimeSpan(48, 0, 0));
DateTime jeudi = laDate.Add(new TimeSpan(72, 0, 0));
DateTime vendredi = laDate.Add(new TimeSpan(96, 0, 0));
DateTime samedi = laDate.Add(new TimeSpan(120, 0, 0));
DateTime dimanche = laDate.Subtract(new TimeSpan(24, 0, 0));
//Création des jours - ajouter les blocs existants
jours[0] = new GrilleJour("Dimanche", dimanche, 1, 40, 20, grfx, loader, this);
jours[1] = new GrilleJour("Lundi", lundi, 2, 140, 20, grfx, loader, this);
jours[2] = new GrilleJour("Mardi", mardi, 3, 240, 20, grfx, loader, this);
jours[3] = new GrilleJour("Mercredi", mercredi, 4, 340, 20, grfx, loader, this);
jours[4] = new GrilleJour("Jeudi", jeudi, 5, 440, 20, grfx, loader, this);
jours[5] = new GrilleJour("Vendredi", vendredi, 6, 540, 20, grfx, loader, this);
jours[6] = new GrilleJour("Samedi", samedi, 7, 640, 20, grfx, loader, this);
}
示例6: Image_Tap
private void Image_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
if (cyclePivot.Items.Count == 0)
{
MessageBox.Show("Please define at least one cycle before continuing", "No cycles have been defined", MessageBoxButton.OK);
return;
}
dateTimeRunning = DateTime.Now;
dateTimeEnd = dateTimeRunning.Add((TimeSpan)timeSpanPicker.Value);
int i = currentCycle;
//for (int i = 0; i < App.ViewModel.CycleCounter - 1; i++)
//{
DateTime dtEnd = dateTimeEndCycles[i];
DateTime dtRunning = dateTimeRunningCycles[i];
PivotItem pItem = (PivotItem)cyclePivot.Items[i];
TimeSpanPicker picker = (TimeSpanPicker)pItem.Content;
dateTimeEndCycles[i] = dateTimeRunning.Add((TimeSpan)picker.Value);
dateTimeRunningCycles[i] = DateTime.Now;
//}
//Time is zero, so exit
if (timeSpanPicker.Value == TimeSpan.FromTicks(0))
return;
PlayPause.Source = (ImageSource)new ImageSourceConverter().ConvertFromString("Images/appbar.transport.pause.rest.png");
if (!dispatcherTimer.IsEnabled)
{
dispatcherTimer.Start();
}
else
{
dispatcherTimer.Stop();
PlayPause.Source = (ImageSource)new ImageSourceConverter().ConvertFromString("Images/appbar.transport.play.rest.png");
}
}
示例7: IntersectDates
private static bool IntersectDates(DateTime one, DateTime two, TimeSpan tone, TimeSpan ttwo)
{
if (one == two || one.Add(tone) == two.Add(ttwo))
{
return false;
}
else if (one < two)
{
if (one.Add(tone) > two)
{
return false;
}
if (one.Add(tone) > two.Add(ttwo))
{
return false;
}
}
else
{
if (two.Add(ttwo) > one)
{
return false;
}
if (one.Add(tone) < two.Add(ttwo))
{
return false;
}
}
return true;
}
示例8: ConvertFromSubsonicTimestamp
public static DateTime ConvertFromSubsonicTimestamp(double timestamp, bool asLocalTime = true)
{
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
TimeSpan ts = TimeSpan.FromSeconds(timestamp / 1000); //subsonic seems to measure in ms rather than seconds
if (asLocalTime)
return origin.Add(ts).ToLocalTime();
return origin.Add(ts);
}
示例9: FillGuide
protected override async Task FillGuide(DateTime date) {
// Nolasīto bloku saturs. Viens [bloka] raidījums var būt vairākas reizes dienā, bet tam atbilst viena bloka lappuse.
var episodes=new Dictionary<int, Episode>(12);
bool previousIsPast=true; // Vai iepriekšējais bloks ir pagātnē. Lieto pašreizējā bloka noteikšanai (jo tas nekā neizceļās).
string episodeCaption=null; // Pašreizējā bloka nosaukums.
var sb=new StringBuilder(200);
foreach (var xEpisode in await GetFragments("http://radiomayak.ru/schedule/index/date/"+date.ToString("dd-MM-yyyy"))) {
string className=xEpisode.Attribute("class").Value;
if (className == "b-schedule__list-sub-list") {
// Dienas programmā pašreizējais bloks ir izvērsts, paņem no tā visus raidījumus.
foreach (var fragment in xEpisode.Elements("div")) {
var data=fragment.Element("div").Elements("div");
AddBroadcast(date.Add(TimeSpan.Parse(data.ElementAt(0).Value.Substring(0, 5))), // hh:mm
GetCaption(data, episodeCaption), GetDescription(data, sb));
}
} else {
var data=xEpisode.Element("div").Elements("div");
var link=data.ElementAt(1).Element("h5").Element("a");
if (previousIsPast && !className.EndsWith("past-show")) {
// Tā kā pirmais bloka raidījums sākas kopā ar bloku, iegaumē tikai tā nosaukumu.
episodeCaption=link.Value;
} else {
if (episodeCaption == null) {
// Raidījumiem pirms pašreizējā paņem tikai bloka laiku un nosaukumu.
AddBroadcast(date.Add(TimeSpan.Parse(data.ElementAt(0).Value)), // hh:mm
link.Value, null);
} else {
episodeCaption=link.Value;
string episodeTime=data.ElementAt(0).Value; // hh:mm
int id=int.Parse(idRx.Match(link.Attribute("href").Value).Groups[1].Value);
Episode episode;
if (!episodes.TryGetValue(id, out episode)) {
// Nākošajiem raidījumiem bloka saturu izgūst no atsevišķas lappuses.
episode=new Episode(await GetFragments("http://radiomayak.ru"+link.Attribute("href").Value));
episodes.Add(id, episode);
}
bool inBlock=false; // Vai pašreizējie bloka raidījumi atbilst atlasāmajam laikam.
for (int n=episode.StartIdx; n < episode.FragmentsCount; n++) {
var fragment=episode.Fragments.ElementAt(n);
data=fragment.Element("div").Elements("div");
if (data.Count() == 2) { // Starp blokiem ir atdalītāji, kurus veido mazāk div elementu.
if (inBlock) { episode.StartIdx=n+1; break; }
continue;
}
string fragmentTime=data.ElementAt(0).Value.Substring(0, 5); // hh:mm (Substring nogriež atdalītāju un beigu laiku)
if (episodeTime == fragmentTime) inBlock=true;
if (inBlock)
AddBroadcast(date.Add(TimeSpan.Parse(fragmentTime)), GetCaption(data, episodeCaption), GetDescription(data, sb));
}
}
}
previousIsPast=className.EndsWith("past-show");
}
}
}
示例10: AreEqualsValidatesDatesWithinThreshold
public void AreEqualsValidatesDatesWithinThreshold()
{
var date1 = new DateTime(2016, 3, 1, 12, 34, 56);
var date2 = date1.Add(1.Seconds());
LoggerAssert.AreEqual(date1, date2, 2.Seconds(), "Dates should be equal +/- 2 seconds");
var date3 = date1.Add(5.Seconds());
TestUtils.ExpectException<AssertFailedException>(() => LoggerAssert.AreEqual(date1, date3, 2.Seconds(), "This assert should fail!"),
"5 seconds are too big a difference...");
}
示例11: Main
static void Main(string[] args)
{
long javams = 1339714653449L;
DateTime UTCBaseTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime dt = UTCBaseTime.Add(new TimeSpan(javams * TimeSpan.TicksPerMillisecond)).ToLocalTime();
System.Console.Out.WriteLine(dt.Ticks);
System.Console.Out.WriteLine(DateTime.Now.Ticks);
System.Console.Out.WriteLine(DateTime.Parse("2012.06.14 02:57:23"));
System.Console.Out.WriteLine(new DateTime(dt.Ticks));
System.Console.Out.WriteLine(new DateTime(DateTime.Now.Ticks));
double Latitude = ConvertCoordinates("N4753.0418");
double Longitude = ConvertCoordinates("E00820.8429");
double Altitude = double.Parse("1015.4", NumberFormatInfo.InvariantInfo);
System.Console.Out.WriteLine(new DateTime(634755390850000000).AddDays(-1));
System.Console.Out.WriteLine(new DateTime(UTCBaseTime.Add(new TimeSpan(1339942290000L * TimeSpan.TicksPerMillisecond)).Ticks));
// Type serviceType = typeof(LiveInputService.LiveInputServiceImpl);
// ServiceHost host = new ServiceHost(serviceType,new Uri[]{new Uri("gps")});
//host.Open();
// AnrlService.AnrlServiceImpl service = new AnrlService.AnrlServiceImpl();
// service.start();
Thread.Sleep(Int32.MaxValue);
/*int PORT = 1337;
TcpListener server;
server = new TcpListener(IPAddress.Any, PORT);
server.Start();
server.BeginAcceptTcpClient(ClientConnected, server);
Thread.Sleep(Int32.MaxValue);
/*
AnrlDB.AnrlDataContext db = new AnrlDB.AnrlDataContext();
db.DatabaseExists();
db.CreateDatabase();*/
/*
string path = @"C:\Users\Helios6x\Downloads\flags_style1_medium";
DirectoryInfo dir = new DirectoryInfo(path);
AnrlDB.AnrlDataContext db = new AnrlDB.AnrlDataContext();
foreach (FileInfo fi in dir.GetFiles().Where(p=>p.Extension==".png"))
{
Image i = Image.FromFile(fi.FullName);
t_Picture pic = new t_Picture();
pic.Name = fi.Name.Replace(fi.Extension,"").Trim();
pic.isFlag = true;
MemoryStream ms = new MemoryStream();
i.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
pic.Data = ms.ToArray();
db.t_Pictures.InsertOnSubmit(pic);
}
db.SubmitChanges();*/
}
示例12: CheckAvail
public static bool CheckAvail(this TableAvailability ta, DateTime date, DateTime startTime, DateTime endTime)
{
var TAStartTime = date.Add(DateTime.ParseExact(ta.StartTime.Trim(), "h:mm tt", CultureInfo.InvariantCulture).TimeOfDay);
var TAEndTime = date.Add(DateTime.ParseExact(ta.EndTime.Trim(), "h:mm tt", CultureInfo.InvariantCulture).TimeOfDay);
if ((TAStartTime <= startTime && TAEndTime >= endTime)
|| (TAStartTime >= startTime && TAEndTime <= endTime)
|| (TAStartTime < startTime && TAEndTime > startTime)
|| (TAStartTime < endTime && TAEndTime > endTime))
return true;
else
return false;
}
示例13: EPGEntry
public EPGEntry(ushort service, string name, string description, DateTime start, TimeSpan duration)
{
// Main
Text = string.Format("{0} (0x{0:x})", service);
// Load all
SubItems.Add(start.ToString());
SubItems.Add(start.Add(duration).TimeOfDay.ToString());
SubItems.Add(name);
SubItems.Add(description);
// Create for compare
CompareData = new object[] { service, start, start.Add(duration), name };
}
示例14: AddEvent
public void AddEvent(DateTime date, string title, string location)
{
Event newEvent = new Event(date, title, location);
title.Add(title.ToLower(), newEvent);
date.Add(newEvent);
Messages.EventAdded();
}
示例15: SchoolDayLessonsTest
public void SchoolDayLessonsTest()
{
TimeSpan lessonDuration = Duration.Minutes( 50 );
TimeSpan shortBreakDuration = Duration.Minutes( 5 );
TimeSpan largeBreakDuration = Duration.Minutes( 15 );
DateTime now = ClockProxy.Clock.Now;
DateTime todaySchoolStart = new DateTime( now.Year, now.Month, now.Day, 8, 0, 0 );
TimeBlock lesson1 = new TimeBlock( todaySchoolStart, lessonDuration );
TimeBlock break1 = new TimeBlock( lesson1.End, shortBreakDuration );
TimeBlock lesson2 = new TimeBlock( break1.End, lessonDuration );
TimeBlock break2 = new TimeBlock( lesson2.End, largeBreakDuration );
TimeBlock lesson3 = new TimeBlock( break2.End, lessonDuration );
TimeBlock break3 = new TimeBlock( lesson3.End, shortBreakDuration );
TimeBlock lesson4 = new TimeBlock( break3.End, lessonDuration );
Assert.AreEqual( lesson4.End,
todaySchoolStart.Add( lessonDuration ).
Add( shortBreakDuration ).
Add( lessonDuration ).
Add( largeBreakDuration ).
Add( lessonDuration ).
Add( shortBreakDuration ).
Add( lessonDuration ) );
}