Use UTC timezone in Javascript date - javascript

This is the code I currently have but I am struggling to convert it to UTC
var today = Date.UTC(new Date());
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
var H = today.getHours();
var i = today.getMinutes();
var s = today.getSeconds();
if(dd<10) {
dd = '0'+dd
}
if(mm<10) {
mm = '0'+mm
}
today = yyyy + '-' + mm + '-' + dd + ' ' + H + ':' + i + ':' + s;
Any ideas on how I can get this working in the same timestamp format? Thanks!

Date objects are always stored in UTC - the .getXxx() functions you're calling implicitly convert that UTC time into your local timezone.
To extract the relevant fields in UTC time instead you should be using the .getUTCxxx() family of functions.
//
// returns the date and time in format 'YYYY-MM-DD hh:mm:ss'
//
// will take a `Date` object, or use the current system
// time if none is supplied
//
function UTC_DateTime(date) {
if (date === undefined) {
date = new Date();
}
function pad2(n) {
return (n < 10) ? ('0' + n) : n;
}
return date.getUTCFullYear() + '-' +
pad2(date.getUTCMonth() + 1) + '-' +
pad2(date.getUTCDay()) + ' ' +
pad2(date.getUTCHours()) + ':' +
pad2(date.getUTCMinutes()) + ':' +
pad2(date.getUTCSeconds());
}

Related

convert javascript date to c# datetime

I am trying to convert javascript date to c# datetime
JavaScript Code
var date = new Date();
var day = date.getDay();
var month = date.getMonth();
var year = date.getFullYear();
var hour = date.getHours();
var minute = date.getMinutes();
var second = date.getSeconds();
// After this construct a string with the above results as below
var JSDateString = year+ "-" + month + "-" + day + " " + hour + ':' + minute + ':' + second;
C# Code
var JSDateString = "2016-04-02 17:15:45"; // I receive date string via Ajax call in this format
var dt = DateTime.ParseExact(JSDateString , "yyyy-mm-dd HH:mm:ss", CultureInfo.InvariantCulture);
I get invalid datetime format exception. I researched other options in internet but I didn't find any specific answer on how to convert JavaScript datetime to C# datetime.
mm is for minutes, you want MM for month:
var dt = DateTime.ParseExact(JSDateString , "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
This might help with the JavaScript side:
function getDate() {
var date = new Date(),
year = date.getFullYear(),
month = (date.getMonth() + 1).toString(),
formatedMonth = (month.length === 1) ? ("0" + month) : month,
day = date.getDate().toString(),
formatedDay = (day.length === 1) ? ("0" + day) : day,
hour = date.getHours().toString(),
formatedHour = (hour.length === 1) ? ("0" + hour) : hour,
minute = date.getMinutes().toString(),
formatedMinute = (minute.length === 1) ? ("0" + minute) : minute,
second = date.getSeconds().toString(),
formatedSecond = (second.length === 1) ? ("0" + second) : second;
return year + "-" + formatedMonth + "-" + formatedDay + " " + formatedHour + ':' + formatedMinute + ':' + formatedSecond;
};
View a fiddle here: https://jsfiddle.net/kpduncan/de8j318k/
I had too do something like this when I building an application due to not being allowed to add thrid party JS and needing support back to IE8.
As you can see on the MSDN, mm is for minutes (00 - 59) whereas MM is for the month (01 - 12).
var JSDateString = "2016-04-02 17:15:45";
var formatCode = "yyyy-MM-dd HH:mm:ss";
var dt = DateTime.ParseExact(JSDateString , formatCode, CultureInfo.InvariantCulture);
You can see that mm is for minutes because you already use it in your HH:mm:ss.

How to alert current date in yyyy-mm-dd hrs:min:sec format in javascript?

In my program i need to alert current date with time in specific format(2015-11-18 12:23:00) so i am write like this
var date = new Date();
alert(date);
but the result is Wed Nov 18 2015 12:24:28 GMT+0530 (India Standard Time).
and also i am try like this
<script>
var d = new Date();
var c = new Date();
alert(formatDate(c));
alert(formatDate(d));
function formatDate(d)
{
var month = d.getMonth();
var day = d.getDate();
var hours = d.getHours();
var minutes = d.getMinutes();
month = month + 1;
month = month + "";
if (month.length == 1)
{
month = "0" + month;
}
day = day + "";
if (day.length == 1)
{
day = "0" + day;
}
hour = hour + "";
if (hour.length == 1)
{
hour = "0" + hour;
}
minute = minute + "";
if (minute.length == 1)
{
minute = "0" + minute;
}
return d.getFullYear()+month + '' + day + ''+ hour + '' + minute + '';
}</script>
it is also not working properly.
how can i do this in javascript and also i need to passed the veriable to database in another php file. please help me how can i do this
I think this below code are helpful us.
function getDateTimeFormate () {
now = new Date();
year = "" + now.getFullYear();
month = "" + (now.getMonth() + 1); if (month.length == 1) { month = "0" + month; }
day = "" + now.getDate(); if (day.length == 1) { day = "0" + day; }
hour = "" + now.getHours(); if (hour.length == 1) { hour = "0" + hour; }
minute = "" + now.getMinutes(); if (minute.length == 1) { minute = "0" + minute; }
second = "" + now.getSeconds(); if (second.length == 1) { second = "0" + second; }
return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
}
To get date time formate like.
alert(getDateTimeFormate());
// example alert message: 2011-05-18 15:20:12
Try this..
<script>
var currentdate = new Date();
var datetime = currentdate.getFullYear() + "-"
+ (currentdate.getMonth()+1) + "-"
+ currentdate.getDate() + " "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
alert(datetime);
</script>
Output:2015-11-18 12:46:52
Demo:http://js.do/code/73749
Please try the following code:
Number.prototype.padLeft = function(base,chr){
var len = (String(base || 10).length - String(this).length)+1;
return len > 0? new Array(len).join(chr || '0')+this : this;
}
var d = new Date;
function formatDate(d){
dformat = [ (d.getMonth()+1).padLeft(),
d.getDate().padLeft(),
d.getFullYear()].join('-')+
' ' +
[ d.getHours().padLeft(),
d.getMinutes().padLeft(),
d.getSeconds().padLeft()].join(':');
return dformat;
}
alert(formatDate(d));
It will return : 11-18-2015 12:17:02. And to pass the value to a php code check this: How to pass JavaScript variables to PHP?
This might be useful
Date.prototype.yyyy = function() {
var yy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString();
var dd = this.getDate().toString();
var hh = this.getHours().toString();
var min = this.getMinutes().toString();
var ss = this.getSeconds().toString();
return yy +"-" +(mm[1]?mm:"0"+mm[0]) + "-" +(dd[1]?dd:"0"+dd[0])+" "+(hh[1]?hh:"0"+hh[0])+":"+(min[1]?min:"0"+min[0])+":"+(ss[1]?ss:"0"+ss[0]);
};
d = new Date();
d.yyyy();
From the below function you will get all the details you want to show use it according to your need
getMonth() - Returns a zero-based integer (0-11) representing the month of the year.
getDate() - Returns the day of the month (1-31).
getDay() - Returns the day of the week (0-6). 0 is Sunday, 6 is Saturday.
getHours() - Returns the hour of the day (0-23).
getMinutes() - Returns the minute (0-59).
getSeconds() - Returns the second (0-59).
getMilliseconds() - Returns the milliseconds (0-999).
getTimezoneOffset() - Returns the number of minutes between the machine local time and UTC.
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){
dd='0'+dd
}
if(mm<10){
mm='0'+mm
}
var today = dd+'/'+mm+'/'+yyyy;
document.getElementById("DATE").value = today;
Use this code:
var sec = d.getSeconds();
return d.getFullYear()+'-'+month + '-' + day + ' '+ hour + ':' + minute + ':'+sec;
instead of:
return d.getFullYear()+month + '' + day + ''+ hour + '' + minute + '';

javascript date format conversion [duplicate]

This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 9 years ago.
I am using pikaday's datepicker. It gives me output "Fri Sep 20 2013". How can I convert this date into yyyy-mm-dd format and I also would want following date of this selected date and set that one to another element.
I tried this code
function formattedDate() {
var fromdate = new Date(document.getElementById('datepicker').value);
var dd = fromdate.getDate();
var mm = fromdate.getMonth()+1; //January is 0!
var yyyy = fromdate.getFullYear();
if(dd < 10)
{
dd = '0'+ dd;
}
if(mm < 10)
{
mm = '0' + mm;
}
var fromdate1 = dd+'/'+mm+'/'+yyyy;
fromdate.setDate(fromdate.getDate() + 2);
document.getElementById('datepicker').value = fromdate1;
var newdate = fromdate;
document.getElementById('datepicker1').value = newdate;
//alert(newdate1);
}
But it doesn't work.
var date = new Date(dateString);
var year = date.getFullYear(), month = (date.getMonth() + 1), day = date.getDate();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
var properlyFormatted = "" + year + month + day;
Or
var date = new Date(dateString);
var properlyFormatted = date.getFullYear() + ("0" + (date.getMonth() + 1)).slice(-2) + ("0" + date.getDate()).slice(-2);
Use momentjs — it's a library available for using in browser and node projects
In your case you should use this pattern:
moment().format("YYYY-mm-D");
And you can try it in console on momentjs's site:

Combine date and time string into single date with javascript

I have a datepicker returning a date string, and a timepicker returning just a time string.
How should I combine those into a single javascript Date?
I thought I found a solution in Date.js. The examples shows an at( )-method, but I can't find it in the library...
You can configure your date picker to return format like YYYY-mm-dd (or any format that Date.parse supports) and you could build a string in timepicker like:
var dateStringFromDP = '2013-05-16';
$('#timepicker').timepicker().on('changeTime.timepicker', function(e) {
var timeString = e.time.hour + ':' + e.time.minute + ':00';
var dateObj = new Date(datestringFromDP + ' ' + timeString);
});
javascript Date object takes a string as the constructor param
Combine date and time to string like this:
1997-07-16T19:20:15
Then you can parse it like this:
Date.parse('1997-07-16T19:20:15');
You could also use moment.js or something similar.
For plain JavaScript:
combineDateAndTime = function(date, time) {
timeString = time.getHours() + ':' + time.getMinutes() + ':00';
var year = date.getFullYear();
var month = date.getMonth() + 1; // Jan is 0, dec is 11
var day = date.getDate();
var dateString = '' + year + '-' + month + '-' + day;
var combined = new Date(dateString + ' ' + timeString);
return combined;
};
You can concatenate the date and time, and then use moment to get the datetime
const date = '2018-12-24';
const time = '23:59:59';
const dateTime = moment(`${date} ${time}`, 'YYYY-MM-DD HH:mm:ss').format();
Boateng's example fails in cases where time consisted of hours, minutes, days or months that ranged from values 0-9 as getDate(), getMonth() etc... will return 1 digit in these cases and the time string will fail and an invalid date is returned:
function CombineDateAndTime(date, time) {
const mins = ("0"+ time.getMinutes()).slice(-2);
const hours = ("0"+ time.getHours()).slice(-2);
const timeString = hours + ":" + mins + ":00";
const year = date.getFullYear();
const month = ("0" + (date.getMonth() + 1)).slice(-2);
const day = ("0" + date.getDate()).slice(-2);
const dateString = "" + year + "-" + month + "-" + day;
const datec = dateString + "T" + timeString;
return new Date(datec);
};
Unfortunately do not have enough rep to comment
David's example with slight modifications:
function CombineDateAndTime(date, time) {
var timeString = time.getHours() + ':' + time.getMinutes() + ':00';
var ampm = time.getHours() >= 12 ? 'PM' : 'AM';
var year = date.getFullYear();
var month = date.getMonth() + 1; // Jan is 0, dec is 11
var day = date.getDate();
var dateString = '' + year + '-' + month + '-' + day;
var datec = dateString + 'T' + timeString;
var combined = new Date(datec);
return combined;
};
Concate date and time with moment JS which also works on firefox,
let d1 = moment().format('MM/DD/YYYY');
let dateTimeOpen = moment(d1 + ' ' + model.openingTime).format('YYYY-MM-DD HH:mm:ss');
let dateTimeClose = moment(d1 + ' ' + model.closingTime).format('YYYY-MM-DD HH:mm:ss');
const date = "2022-12-27";
const time = "16:26:42";
new Date(`${date}T${time});
output
Date Tue Dec 27 2022 16:26:42 GMT+0100 (Central European Standard Time)

Ajax get Date in dd/mm/yyyy format

var d = new Date();
var today_date = d.getDate() + '/' + month_name[d.getMonth()] + '/' + d.getFullYear();
This is how I am getting a date. It works with a slight problem. For todays date 7th of June 2011 it returns 7/11/2011, what i want it to return is 07/11/2011?
Anyone know how?
Well, you could simply check the length of d.getDate()and if it's 1 then you add a zero at the beginning. But you would like to take a look at format() to format your dates?
Like so:
("0"+1).slice(-2); // returns 01
("0"+10).slice(-2); // returns 10
Complete example:
var d = new Date(2011,1,1); // 1-Feb-2011
var today_date =
("0" + d.getDate()).slice(-2) + "/" +
("0" + (d.getMonth() + 1)).slice(-2) + "/" +
d.getFullYear();
// 01/02/2011
Try this (http://blog.stevenlevithan.com/archives/date-time-format):
var d = new Date();
d.format("dd/mm/yyyy");
Try this, this is more understandable.:
var currentTime = new Date();
var day = currentTime.getDate();
var month = currentTime.getMonth() + 1;
var year = currentTime.getFullYear();
if (day < 10){
day = "0" + day;
}
if (month < 10){
month = "0" + month;
}
var today_date = day + "/" + month + "/" + year;
document.write(today_date.toString());
And result is :
07/05/2011

Categories

Resources