Javascript datetime issue - converting to utc - javascript

My database value is this
2020-03-08 20:44:00
But in javascript. It display
Mon Mar 09 2020 09:44:00 GMT+0800 (Singapore Standard Time)
Want i want to display on UI
2020-03-08 20:44:00
or
2020-03-08
Is there a way to remove the timezone and get only the actual value from the database.

toISOString is not a proper way to get date into DateTime. please follow the below method to get a date from DateTime.
var date = new Date("2020-03-08 20:44:00");
var year = date.getFullYear();
var month = (1 + date.getMonth()).toString();
month = month.length > 1 ? month : '0' + month;
var day = date.getDate().toString();
day = day.length > 1 ? day : '0' + day;
var newDate = year + '-' + month + '-' + day;
console.log("Date plush time - "+date);
console.log("Only Date - "+newDate);

You're using the silently using Date object's .toString() method which converts the UTC date (that your database is storing) into a time in the current time zone.
If date is the variable that you get from your database, then you can format it like you want it like this:
let dateString = date.toISOString().replace('T', ' ').replace(/\..+/, '')
This will take your date, convert it into an ISO string (in the form 2020-01-10T03:09:24.551Z) and replace the T with a space and everything after the decimal with nothing.

Try this.
let d = new Date('2020-03-08 20:44:00');
console.log(`${d.getFullYear()}-${d.getMonth() < 10 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1}-${d.getDate() < 10 ? '0' + (d.getDate()): d.getDate()}`);

You can take each part of the date and construct your own format
example:
let formatted_date = my_date.getFullYear() + "-" + (my_date.getMonth() + 1) + "-" + my_date.getDate()
in this example: my_date hold the date you want to display.

If you're able to use a library, use moment.js
https://momentjs.com/docs/#/displaying/
moment("2020-03-08 20:44:00").format("YYYY-MM-DD");
or
moment(new Date("2020-03-08 20:44:00")).format("YYYY-MM-DD");
It can even change the time to utc
https://momentjs.com/guides/#/parsing/local-utc-zone/
moment.utc("2020-03-08 20:44:00").format("YYYY-MM-DD");
hope this helps :)

Subtract your timezone offset milliseconds.
var dt = new Date('2020-03-08 20:44:00');
dt = new Date(dt.getTime()-dt.getTimezoneOffset()*60000);
console.log(dt.toUTCString());
var mo = dt.getUTCMonth()+1, d = dt.getUTCDate(), h = dt.getUTCHours();
var m = dt.getUTCMinutes(), s = dt.getUTCSeconds();
if(mo < 10)mo = '0'+mo;
if(d < 10)d = '0'+d;
if(h < 10)h = '0'+h;
if(m < 10)m = '0'+m;
if(s < 10)s = '0'+s;
console.log(dt.getUTCFullYear()+'-'+mo+'-'+d+' '+h+':'+m+':'+s);

Related

How to convert strings of the format "6 Dec, 2022 " to a date? [duplicate]

In BIRT, i have a column containing a datetime stored as a string. I need to convert these string to datetime format and put the result in another column using Javascript.
The string is the form of: for example: Fri 21 Feb 2014, 09:40 AM.
Hence this when converted to a datetime format and exported to excel, the column should be treat as a date.
Can any one of you help me to do it?
Cheers,
Other answers do not take into consideration this question is in a BIRT context.
Create a computed column in your dataset, with "Date time" as datatype
Enter as expression:
new Date(row["myDateStringField"]);
Where "myDateStringField" is your DateTime column in a String format. Then use this computed column in your report instead of the String column.
That's it!
Checkout momentjs!
You can parse your time of any format like
moment("12-25-1995", "MM-DD-YYYY");
In your case, you don't even have to specify the format. It automatically recognizes it.
And you can output ISO format or convert it to a Javascript Date object.
This is extremely easy to do with javascript. The following code will make a date in a format that Excel will recognize as a date.
http://jsfiddle.net/bbankes/d7SwQ/
var dateString = 'Fri 21 Feb 2014, 09:40 AM';
var date = new Date(dateString);
var yr = date.getFullYear();
var mo = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var hr = hours < 10 ? '0' + hours : hours;
var minutes = date.getMinutes();
var min = (minutes < 10) ? '0' + minutes : minutes;
var seconds = date.getSeconds();
var sec = (seconds < 10) ? '0' + seconds : seconds;
var newDateString = yr + '-' + mo + '-' + day;
var newTimeString = hr + ':' + min + ':' + sec;
var excelDateString = newDateString + ' ' + newTimeString;
If you just want to reformat 'Fri 21 Feb 2014, 09:04 AM' as '2014-02-21 09:04', then the following will do:
function stringToTimestamp(s) {
var t = s.match(/[\d\w]+/g);
var months = {jan:'01',feb:'02',mar:'03',apr:'04',may:'05',jun:'06',
jul:'07',aug:'08',sep:'09',oct:'10',nov:'11',dec:'12'};
function pad(n){return (n<10?'0':'') + +n;}
var hrs = t[4] % 12;
hrs += /pm$/i.test(t[6])? 12 : 0;
return t[3] + '-' + months[t[2].toLowerCase()] + '-' + pad(t[1]) + ' ' +
pad(hrs) + ':' + pad(t[5]);
}
console.log(stringToTimestamp('Fri 21 Feb 2014, 09:04 AM')); // 2014-02-21 09:04
use the ISO format: YYYY-MM-DDTHH:MM:SS or YYYY-MM-DD
new Date('2011-04-11T11:51:00');
or
new Date('2011-04-11');

Converting Date time formats

What's the best way to convert date time formats using javascript?
I have this.. "2015-08-06T00:39:08Z"
and would like to change it to
"06/08/2015 12:39pm"
You could do it manually by instantiating a Date object:
var d = new Date('2015-08-06T00:39:08Z');
Then using the Date methods (like getDay or getUTCFullYear) to get the information needed and build the formatted string.
Or, if you don't mind relying on a library, you could use http://momentjs.com/ that provides a lot of methods, and particularly the format method: http://momentjs.com/docs/#/displaying/format/
// Example with moment.js
var formattedDate = moment('2015-08-06T00:39:08Z').format("MM/DD/YYYY hh:mma");
alert(formattedDate);
Use newDate() method, then Date Get Methods. Examples are explained on w3Schools
Method Description
getDate() Get the day as a number (1-31)
getDay() Get the weekday as a number (0-6)
getFullYear() Get the four digit year (yyyy)
getHours() Get the hour (0-23)
getMilliseconds() Get the milliseconds (0-999)
getMinutes() Get the minutes (0-59)
getMonth() Get the month (0-11)
getSeconds() Get the seconds (0-59)
getTime() Get the time (milliseconds since January 1, 1970)
With pure javascript:
code:
function formatDate(input) {
var datePart = input.match(/\d+/g),
year = datePart[0], // get only two digits
month = datePart[1],
day = datePart[2];
var h = parseInt(input.substr(input.indexOf("T") + 1, 2));
var m = parseInt(input.substr(input.indexOf(":") + 1, 2));
var dd = "AM";
if (h >= 12) {
h = hh - 12;
dd = "PM";
}
if (h == 0) {
h = 12;
}
m = m < 10 ? "0" + m : m;
alert(day + '/' + month + '/' + year + ' ' + h.toString() + ':' + m.toString() + dd);
}
formatDate('2015-08-06T00:39:08Z'); // "18/01/10"

Converting to a Date Object from a datetime-local Element

I am using the HTML5 element datetime-local. I need to have two formats of the date. One as a date object the other as a string. I am going to store the date object in the database and I am going to use the string to set the datetime-local form input.
I need to convert this string to a date object:
"2014-06-22T16:01"
I can't seem to get the correct time. This is what I am getting. The time not correct.
Sun Jun 22 2014 09:01:00 GMT-0700 (PDT)
This is the how I am formating the date:
function formatTime(_date) {
var _this = this,
date = (_date) ? _date : new Date(),
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear(),
hour = date.getHours(),
minute = date.getMinutes(),
seconds = date.getSeconds(),
function addZero(num) {
return num > 9 ? num : '0' + num;
}
minute = addZero(minute);
seconds = addZero(seconds);
hour = addZero(hour);
day = addZero(day);
month = addZero(month);
return year + '-' + month + '-' + day + 'T' + hour + ':' + minute;
};
Example:
http://codepen.io/zerostyle/pen/gwpuK/
If you are trying to get an ISO 8601 date string, you can try Date.prototype.toISOString. However, it always uses UTC. If you want to include the local timezone, use something like the following:
/* Return a string in ISO 8601 format with current timezone offset
** e.g. 2014-10-02T23:31:03+0800
** d is a Date object, or defaults to current Date if not supplied.
*/
function toLocalISOString(d) {
// Default to now if no date provided
d = d || new Date();
// Pad to two digits with leading zeros
function pad(n){
return (n<10?'0':'') + n;
}
// Pad to three digits with leading zeros
function padd(n){
return (n<100? '0' : '') + pad(n);
}
// Convert offset in mintues to +/-HHMM
// Note change of sign
// e.g. -600 => +1000, +330 => -0530
function minsToHHMM(n){
var sign = n<0? '-' : '+';
n = Math.abs(n);
var hh = pad(n/60 |0);
var mm = pad(n%60);
return sign + hh + mm;
}
var offset = minsToHHMM(d.getTimezoneOffset() * -1);
return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()) +
'T' + pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds()) +
'.' + padd(d.getMilliseconds()) + offset;
}
console.log(toLocalISOString(new Date())); // 2014-06-23T07:58:04.773+0800
Edit
The above probably misses your question, which seems to be;
I need to convert this string to a date object: "2014-06-22T16:01"
Presumaly you want to treat it as a local time string. ECMA-262 says that ISO–like strings without a timezone are to be treated as UTC, and that is what your host seems to be doing. So you need a function to create a local Date object from the string:
function parseYMDHM(s) {
var b = s.split(/\D+/);
return new Date(b[0], --b[1], b[2], b[3], b[4], b[5]||0, b[6]||0);
}
console.log(parseYMDHM('2014-06-22T16:01')); // Sun Jun 22 16:01:00 UTC+0800 2014

Convert input type text into date format

I have one input type text:
<input type="text" id="policyholder-dob" name="policyholder-dob" />
I want to type number in this field in mm/dd/yyyy format:
like 01/01/2014
This is my js code but its not working, what mistake have I made?
function dateFormatter(date) {
var formattedDate = date.getDate()
+ '/' + (date.getMonth() + 1) + '/' + date.getFullYear();
return formattedDate;
}
var nextduedate = $("#policyholder-dob").val();
var dateFormatDate = nextduedate.slice(0, 2);
var dateFormatMonth = nextduedate.slice(2, 4);
var dateFormatYear = nextduedate.slice(4, 8);
var totalFormat = dateFormatMonth + '/' + dateFormatDate + '/' + dateFormatYear;
var againNewDate = new Date(totalFormat);
againNewDate.setDate(againNewDate.getDate() + 1);
var todaydate = dateFormatter(againNewDate);
$("#policyholder-dob").prop("value", todaydate);
Any help will be really appreciated.
Thankfully, your input is consistently in this format:
mm/dd/yyyy
So you can convert it to a Date object through a custom function, such as:
function stringToDate(str){
var date = str.split("/"),
m = date[0],
d = date[1],
y = date[2],
temp = [];
temp.push(y,m,d);
return (new Date(temp.join("-"))).toUTCString();
}
Or:
function stringToDate(str){
var date = str.split("/"),
m = date[0],
d = date[1],
y = date[2];
return (new Date(y + "-" + m + "-" + d)).toUTCString();
}
Etc..
Calling it is easy:
stringToDate("12/27/1963");
And it will return the correct timestamp in GMT (so that your local timezone won't affect the date (EST -5, causing it to be 26th)):
Fri, 27 Dec 1963 00:00:00 GMT //Late december
Example
There are various ways to accomplish this, this is one of them.
I'd suggest moment.js for date manipulation. You're going to run into a world of hurt if you're trying to add 1 to month. What happens when the month is December and you end up with 13 as your month. Let a library handle all of that headache for you. And you can create your moment date with the string that you pull from the val. You substrings or parsing.
var d = moment('01/31/2014'); // creates a date of Jan 31st, 2014
var duration = moment.duration({'days' : 1}); // creates a duration object for 1 day
d.add(duration); // add duration to date
alert(d.format('MM/DD/YYYY')); // alerts 02/01/2014
Here's a fiddle showing it off.

Rounding Date to nearest Day in Javascript.

I'm storing data on a per-day basis in localStorage, and in doing so I want to use the date as the "primary key".
I'm using JSON.stringify() and .parse() to store data thus:
localStorage.setItem(datakey, JSON.stringify(dataObject));
dataObject = JSON.parse(localStorage.getItem(datakey));
I want to use the date as the datakey, and the app will just overwrite data recorded earlier in the the day if you record again later in the day.
So I need to round the date to the current day, month and year.
At the moment I'm trying this:
selected_d = $("#date-1").val();
console.log("The date is "+selected_d);
dateArray = selected_d.split("-");
day = dateArray[2];
month = dateArray[1];
year = dateArray[0];
datakey = new Date(year, month, day);
console.log("The datakey is "+datakey);
The reason for using split is that the #date-1 is a jQuery Mobile date and it comes in a yyyy-mm-dd format and I want to use standard UK dd/mm/yy format.
The out put of the the console logs is:
The date is 2014-02-18
The datakey is Tue Mar 18 2014 00:00:00 GMT+0000 (GMT Standard Time)
I know this is because Jan = 0, Feb = 1 and so on.
What I'd really like is some way of creating an "ideal" date object for me. One that only holds days, months and years and one which is in the format DD/MM/YYYY so I can easily query the localStorage. I know I can reconstruct the date by doing:
var displayed_d = (day<10 ? '0' : '') + day + "/"+ (month<10 ? '0' : '') + month_up + "/" + current_d.getFullYear();
but it's not really ideal, is it?
Any ideas?
Why not just form the key using the API?
var d = new Date(); // or wherever the date comes from
var key = function(d) {
function two(n) {
return (n < 10 ? '0' : '') + n;
}
return two(d.getDate()) + '/' + two(d.getMonth() + 1) + '/' + d.getFullYear();
}(d);
You could add that as a function on the Date prototype:
Date.prototype.getDateKey = function() {
function two(n) {
return (n < 10 ? '0' : '') + n;
}
return two(this.getDate()) + '/' + two(this.getMonth() + 1) + '/' + this.getFullYear();
};
Now you can get a key easily:
var dateKey = someRandomDate.getDateKey();
MDN documentation for Date objects.

Categories

Resources