how to get date and time together in javaScript - javascript

Is there a way to get date and time in JS?
I searched in google and saw ways to get the date appart and time appart but not together.
I have a field that calls "Date Time" and i need to show data -12 hours so i need to figure out how to save datetime.
Can someone help?

Use javaScript Date object to work with date and time.
alert(new Date());

Use new Date();
var x = new Date();
You can also fetch each value using .getDay() , .getMonth(), .getYear(), .getHours(), .getMinutes(), .getSeconds()
Like
x.getHours(); // Will give you hours.

use date object of javascript then adjust your date and time combinations
for example, create a function getdateTime which will return dateTime combinations
function getdateTime() {
var date = new Date();
var dataVal=date.getDate() +"/"+ (date.getMonth() + 1)+"/" + date.getFullYear() + ":" + date.getHours() + ":" + date.getMinutes();
return dataVal;
}
var datetime=getdateTime();
console.log("datetime:" +datetime);
output for example : datetime:18/2/2015:14:26
ie current date and time
since months starts from 0 to 11 you have to add 1 to get current month.
you can use other date functions depending upon your requirements.

Related

Create javascript bookmarklet with current year/month/date/hour inserted into URL?

Have this URL I would like to create a bookmarklet for to access the latest data with variables for current UTC date/time (year, month, day and (hour + 6)):
https://www.ogimet.com/cgi-bin/gsynres?ind=02464&lang=en&decoded=yes&ndays=2&ano=2021&mes=07&day=07&hora=18
Is it possible to achieve?
Some JavaScript code can do this.
Thankfully setHours() updates the day / month, etc if it is above 24.
let d = new Date();
d.setHours(d.getHours() + 6);
console.log(`https://www.ogimet.com/cgi-bin/gsynres?ind=02464&lang=en&decoded=yes&ndays=2&ano=${d.getFullYear()}&mes=${d.getMonth()}&day=${d.getDate()}&hora=${d.getHours() + 6}`);
Using bookmarkleter gives us:
javascript:void%20function(){let%20a=new%20Date;a.setHours(a.getHours()+6),window.open(`https://www.ogimet.com/cgi-bin/gsynres%3Find=02464%26lang=en%26decoded=yes%26ndays=2%26ano=${a.getFullYear()}%26mes=${a.getMonth()}%26day=${a.getDate()}%26hora=${a.getHours()+6}`)}();
Modifying your answer (#ScottJodoin) got it to work, using the window.open() method and getUTC methods. The website accepted >24 values for hour in the URL, which made setHours() needless.
let d = new Date();
window.open(`https://www.ogimet.com/cgi-bin/gsynres?ind=02464&lang=en&decoded=yes&ndays=2&ano=${d.getUTCFullYear()}&mes=${d.getUTCMonth()+1}&day=${d.getUTCDate()}&hora=${d.getUTCHours()+6}`,'_self');
Conversion in Bookmarkleter gives:
javascript:void%20function(){let%20a=new%20Date;window.open(`https://www.ogimet.com/cgi-bin/gsynres%3Find=02464%26lang=en%26decoded=yes%26ndays=2%26ano=${a.getUTCFullYear()}%26mes=${a.getUTCMonth()+1}%26day=${a.getUTCDate()}%26hora=${a.getUTCHours()+6}`,%22_self%22)}();

Javascript dates are a day off? [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Changing the format of a date string
(2 answers)
Closed 5 years ago.
I am trying to use a simple date function in my application to pass a date in the format of yyyy-mm-dd such as 2017-07-30 and have it returned in the format of 07/30/2017.
However, when I try this, I supply my date correctly but it outputs one day shorter than what I am looking for.
function format(inputDate) {
var date = new Date(inputDate);
if (!isNaN(date.getTime())) {
var day = date.getDate().toString();
var month = (date.getMonth() + 1).toString();
// Months use 0 index.
return (month[1] ? month : '0' + month[0]) + '/' +
(day[1] ? day : '0' + day[0]) + '/' +
date.getFullYear();
}
}
console.log(format('2017-07-30'));
Here is a fiddle: http://jsfiddle.net/49pptrj4/
Any thoughts as to why this is returning incorrectly?
Result on my end:
From here
Given a date string of "March 7, 2014", [Date.]parse() assumes a local time zone, but given an ISO format such as "2014-03-07" it will assume a time zone of UTC.
Your date string is assumed to be 0:00, or midnight, on the date specified in UTC, the time zone of Greenwich, England. Your browser however takes this time and converts it to your local timezone, which is a few hours behind UTC if you're in the Americas, making the result a day behind.
The following code should work for creating a Date in the local timezone with the correct date.
utcDate = new Date("2017-07-30"); //Date object a day behind
new Date(utcDate.getTime() + utcDate.getTimezoneOffset() * 60000) //local Date
Here the local Date is created by adding time based on the time zone difference. getTimezoneOffset() returns in minutes, so * 60000 is needed to convert to milliseconds.
This might not work in areas ahead of UTC; it might advance an extra day.
Edit: Just checked and getTimezoneOffset() is negative in areas ahead of UTC so it will subtract time correctly.

JavaScript Date() differs when timezone changes

I need to convert my date to mm-dd-yyyy format. So I used a method like this:
var dt=new Date(2016-06-21);
var ddte='';
ddte=(("0" + (dt.getMonth() + 1)).slice(-2))+"-"+(("0" + dt.getDate()).slice(-2))+"-"+dt.getFullYear();
It works fine in my local timezone (GMT+05:30). But when I change my timezone to GMT -5:00, it gives the wrong result: 06-20-2016. The result I want is 06-21-2016.
Can anyone please explain the problem?
How can I get the correct result?
Is it a bug?
Your date passed to Date() constructor will be treated as UTC time zone. Getting the time with Date.getMonth() will get your local time zone. You're probably looking for Date.getUTCMonth().
var dt=new Date("2016-06-21");
var ddte='';
ddte=(("0" + (dt.getUTCMonth() + 1)).slice(-2))+"-"+(("0" + dt.getUTCDate()).slice(-2))+"-"+dt.getUTCFullYear();
console.log(ddte);
Though in this case I see no use for using Date at all; this should suffice:
var parsedDate = "2016-06-21".replace(/(\d{4})-(\d{2})-(\d{2})/, "$2-$3-$1");
console.log(parsedDate);
It isn't a bug. It's just how time zones work (it isn't the same calendar day everywhere in the world at the same time).
If you don't actually want advanced date features (it seems you only want some good old string manipulation) my tip is to just not use Date in the first place.
var parts = "2016-06-21".split("-");
var mdy = parts[1] + "-" + parts[2] + "-" + parts[0];
Add some error checking and you're done.

how to compare date which is given by user to date in javascript..?

In my web-site I am getting a date from user which in format like "dd-mm-yyyy",now I want to get the date which is 7-day before of that user's date.
I am able to get the current date in format "dd-mm-yyyy" but how would I know the date which is one week before user's date in javascript?
If you already have a Date object, use yourDate.setDate(yourDate.getDate() - 7 );
Try this--
var MyDate = new Date('11/30/2012'); //date format in mm/dd/yyyy
MyDate.setDate(MyDate.getDate() -7)
var newDate = MyDate.getMonth()+1 + '/' + MyDate.getDate() + '/' + MyDate.getFullYear()
alert(newDate);
Note- subtracting seven days to a date shifts the month or year and the changes are handled automatically by the Date object.
Why don't you use datejs, it's the best date related js library I have seen. Chcek the documentation here.
http://code.google.com/p/datejs/wiki/APIDocumentation
Search for add method
Set Dates
We can easily manipulate the date by using the methods available for the Date object.
In the example below we set a Date object to a specific date (14th January 2010):
var myDate=new Date();
myDate.setFullYear(2010,0,14);
And in the following example we set a Date object to be 7 days in past:
var myDate=new Date(); //or users date
// myDate will be users current date
myDate.setDate(myDate.getDate()-7);
//now substract 7 days to get the date u want.
Follow the following link
http://www.w3schools.com/js/js_obj_date.asp
Or follow this
http://www.techrepublic.com/article/manipulate-time-and-date-values-with-javascripts-date-object/6076869
You can convert a date string in the format dd-mm-yyyy to a date object using:
function toDate(d) {
d = d.split('-');
return new Date(d[2], --d[1], d[0]);
}
Then use Osiris' answer to add or subtract 7 days.

Comparing today's date with another date in moment is returning the wrong date, why?

I'm using moment.js 1.7.0 to try and compare today's date with another date but the diff function is saying they are 1 day apart for some reason.
code:
var releaseDate = moment("2012-09-25");
var now = moment(); //Today is 2012-09-25, same as releaseDate
console.log("RELEASE: " + releaseDate.format("YYYY-MM-DD"));
console.log("NOW: " + now.format("YYYY-MM-DD"));
console.log("DIFF: " + now.diff(releaseDate, 'days'));
console:
RELEASE: 2012-09-25
NOW: 2012-09-25
DIFF: 1
Ideas?
Based on the documentation (and brief testing), moment.js creates wrappers around date objects. The statement:
var now = moment();
creates a "moment" object that at its heart has a new Date object created as if by new Date(), so hours, minutes and seconds will be set to the current time.
The statement:
var releaseDate = moment("2012-09-25");
creates a moment object that at its heart has a new Date object created as if by new Date(2012, 8, 25) where the hours, minutes and seconds will all be set to zero for the local time zone.
moment.diff returns a value based on a the rounded difference in ms between the two dates. To see the full value, pass true as the third parameter:
now.diff(releaseDate, 'days', true)
------------------------------^
So it will depend on the time of day when the code is run and the local time zone whether now.diff(releaseDate, 'days') is zero or one, even when run on the same local date.
If you want to compare just dates, then use:
var now = moment().startOf('day');
which will set the time to 00:00:00 in the local time zone.
RobG's answer is correct for the question, so this answer is just for those searching how to compare dates in momentjs.
I attempted to use startOf('day') like mentioned above:
var compare = moment(dateA).startOf('day') === moment(dateB).startOf('day');
This did not work for me.
I had to use isSame:
var compare = moment(dateA).isSame(dateB, 'day');

Categories