-1

I have a field that displays a value (lets call it startTime) in ShortTimeString() format & would like to compare this to DateTime.Now in such a way that:

if (startTime.AddMinutes(5) > DateTime.Now){ //do a thing; }

(if startTime was 5 minutes ago or greater, do a thing)

Need a way to convert startTime from a String back to a DateTime so that I can then compare.

Justin
  • 89
  • 10
  • 2
    C# **or** JavaScript...? You should really pick one or the other for the sake of keeping the question properly scoped. Without specifying a language, it could be argued this is too broad and not useful to future readers. – Tyler Roper Sep 30 '19 at 18:07
  • Sorry, edited now to remove c# tag - will stick to jquery – Justin Sep 30 '19 at 18:13
  • Have you tried anything? There are many hundreds of questions about parsing dates, comparing dates, etc. in JavaScript on Stack Overflow... – Heretic Monkey Sep 30 '19 at 18:15
  • There's no such thing as a `DateTime` in JavaScript. There's [the `Date` type](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date), which has documented methods and properties... – Heretic Monkey Sep 30 '19 at 18:18
  • @HereticMonkey ahh. forgive me. Im currently using a mix of JS & c# to perform different functions in my code so thats where my confusion & mixing up of terminologies is coming in – Justin Sep 30 '19 at 18:20

1 Answers1

1

Example of subtracting 2 dates.

var date1 = new Date("6/8/1969 20:30:00");
var date2 = new Date("6/20/1969 19:15:00");

var diff = date2 - date1;

or in your case:

var diff = Date.now() - Date.parse(startTime);  //if startTime is invalid, watchout!

or

 var diff = Date.now() - new Date(startTime);   // I prefer this

useful link here:

How do I get the current date in JavaScript?

T McKeown
  • 12,971
  • 1
  • 25
  • 32
  • Thank You. This is along the lines of what I need, but moreso struggling with figuring out a way to convery startTime back into a Date first before the comparison – Justin Sep 30 '19 at 18:25
  • to parse from string: `var dt = Date.parse("11/30/2011");` I will update my answer. – T McKeown Sep 30 '19 at 18:27
  • Why might diff return NaN here? `startTime = $(".sessionStartTime").text(); var diff = Date.now() - Date.parse(startTime); alert(diff);` – Justin Sep 30 '19 at 19:09
  • the Date.Parse() probably isn't working, check it.. have you tried simple `new Date(startTime);` instead of parse? – T McKeown Sep 30 '19 at 19:12
  • Yup I tried it out. I'm gonna keep messing around and hopefully I can figure it out from here. You've definitely put me on the right path so thank you very much for your time – Justin Sep 30 '19 at 19:18