Bruce Adams
Bruce Adams

Reputation: 12300

.net equivalent of Javascript function

What is the vb.net or c# equivalent of the following javascript?

this.browserTime.value = Math.floor((new Date()).getTime() / 1000);

I'm using httpwebrequest to login in to a site.

PostData header recorded from the browser looks like:

goto=&currentSlave=235acbdcd297c9211eef670c6dfbd64d&browserTime=1245052940&username=username&password=password&go=Sign+In

and the javascript on the page that gets the browsertime value is:

this.browserTime.value = Math.floor((new Date()).getTime() / 1000);

thanks

Upvotes: 0

Views: 1724

Answers (4)

Guffa
Guffa

Reputation: 700612

Translation:

new Date() => DateTime.Now
.getTime() => .Subtract(New DateTime(1970, 1, 1)).TotalMilliseconds
Math.floor() => Math.Floor()

so in VB:

seconds As Double = Math.Floor( _
   DateTime.Now.Subtract(New DateTime(1970, 1, 1)).TotalMilliseconds / 1000
);

and in C#:

double seconds = Math.Floor(
   DateTime.Now.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds / 1000
);

or simply getting the seconds instead of getting milliseconds and dividing, in VB:

seconds As Double = Math.Floor(
   DateTime.Now.Subtract(New DateTime(1970, 1, 1)).TotalSeconds
);

and C#:

double seconds = Math.Floor(
    DateTime.Now.Subtract(New DateTime(1970, 1, 1)).TotalSeconds
);

Upvotes: 2

Ed Sykes
Ed Sykes

Reputation: 1439

Just to add to Johannes comment, I'm guessing that you want to make a comparison between two dates. If so you can use the TimeSpace class like this:

DateTime now = DateTime.Now;
DateTime lastWeek = now.Subtract(TimeSpan.FromDays(7));
TimeSpan difference = now - lastWeek;

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1063609

number of seconds since 1970?

static readonly DateTime epoch = new DateTime(1970, 1, 1);
...
int seconds = (int)Math.Floor((DateTime.Now - epoch).TotalSeconds);

Upvotes: 1

Joey
Joey

Reputation: 354734

That depends on what exactly you need. You seem to want a timestamp. As such you can get it with

DateTime.Now

If you really desperately need the number of seconds since 1970, then you'd have to do some date math as the .NET timestamp isn't based on the UNIX epoch (which would be an implementation detail anyway).

Upvotes: 1

Related Questions