Extract date and time from datetime string in javascript - javascript

My datetime string is of below format:
var sdt = '2022-05-19T13:00:00';
I want to extract the date and time separately and below is my code:
((sdt.getMonth() > 8) ? (sdt.getMonth() + 1) : ('0' + (sdt.getMonth() + 1))) + '/' + ((sdt.getDate() > 9) ? sdt.getDate() : ('0' + sdt.getDate())) + '/' + sdt.getFullYear() + ' ' + (sdt.getHours()) + ':' + (sdt.getMinutes()) + ':00'
From the above code, date is getting extracted correctly but not the time. any help pls?

You can use the Date object and use Date#toLocaleDateString & Date#toLocaleTimeString method to get your time and date
Or even the Date#toLocaleString to get both at the same time !
const sdt = '2022-05-19T13:00:00';
const date = new Date(sdt)
console.log(date.toLocaleString())
console.log(date.toLocaleDateString())
console.log(date.toLocaleTimeString())
Note that you can specify the location to get the date for a current country
date.toLocaleString('en-GB')

I always use a moment.js when dealing with date and time .
Just pass the datetime string and specify the format of the output you want .
import moment from 'moment'
var sdt = '2022-05-19T13:00:00';
let time = moment(sdt).format("HH:mm:ss")
let date = moment(sdt).format("DD/MM/YYYY")
console.log(time) //01:00:00
console.log(date) //19/05/2022
https://momentjs.com/ checkout this page to learn about more formats

use the Date() constructor:
const sdtString = '2022-05-19T13:00:00'; // https://en.wikipedia.org/wiki/ISO_8601
const sdt = new Date(sdtString); // Date Object {}
then to get the respective date / time use:
Date.prototype.toLocaleTimeString()
Date.prototype.toLocaleDateString()
Also, worth remembering that getMonth() gives the month's index (zero based), not the number.

Related

How do I convert UTC DateTime to local DateTime without ending up with a different format

I have specific DateTime values in this format 'YYYY-MM-DDThh:mm:ss.ms' (e.g. '2022-05-10T13:44:00.0000000') and I need to convert them to local DateTime (which is UTC+2 for me) without changing the format (so '2022-05-10T15:44:00.0000000' is the desired result (even better would be without the milliseconds but that would just be the icing on the cake)).
I've searched far and wide but every alleged solution I find either changes the format or doesn't change the time at all.
This is what I have right now, it successfully converts the time to local time but by running it through .toISOString() to get the original format back it converts it back to UTC time.
//Input: event.start.dateTime = '2022-05-10T13:44:00.0000000'
let startDateTime = new Date(event.start.dateTime);
startDateTime.setMinutes(startDateTime.getMinutes() -
startDateTime.getTimezoneOffset());
document.getElementById('ev-start').value =
startDateTime.toISOString().slice(0,16);
//Output: '2022-05-10T13:44:00.000Z'
I couldn't find a clean and satisfying solution so I decided to just to the formatting myself. Here's what I ended up with:
Input: '2022-05-10T13:44:00.0000000'
let startDateTime = new Date(event.start.dateTime);
startDateTime.setMinutes(startDateTime.getMinutes() -
startDateTime.getTimezoneOffset());
let localStartDateTime = startDateTime.getFullYear() + "-" +
(startDateTime.getMonth() + 1).toString().padStart(2, '0') +
"-" + startDateTime.getDate().toString().padStart(2, '0') +
"T" + startDateTime.getHours().toString().padStart(2, '0') +
":" + startDateTime.getMinutes().toString().padStart(2, '0')
+ ":" +
startDateTime.getSeconds().toString().padStart(2, '0');
document.getElementById('ev-start').value =
localStartDateTime;
Output: '2022-05-10T15:44:00'
Hope this helps
const startDateTime = new Date('2022-05-10T13:44:00.0000000');
const outputDateTime = new Date(startDateTime.toString()).toISOString().slice(0, 19);
//document.getElementById('ev-start').value = outputDateTime
console.log(outputDateTime);

Format "2019-08-12T12:10:13Z" to datetime "2019-08-12 12:10:13" in Javascript

We're working on Node-red, where we have a javascript function, where we need to format a datetime looking like this: "2019-08-12T12:10:13Z". The datetime needs to be formatted to "2019-08-12 12:10:13" as we want to store the datetime in our MySQL database as timestamp.
Basically, what we want to do, is to remove the T and Z from the datetime.
This should be fairly easy to do, but we can't find anything on this for javascript.
IMPRORTANT EDIT
Just read that Z stands for UTC, and as we're living in CEST, we want to convert the timezone from UTC to CEST...
If you want to have a special formated Date you have to use library like moment or format it yourself.
const getFormattedDate = (date) => {
return `${date.getFullYear()}-${padNumber(date.getMonth() + 1)}-${padNumber(date.getDate())} ${padNumber(date.getHours())}:${padNumber(date.getMinutes())}:${padNumber(date.getSeconds())}`;
}
const padNumber = (number) => {
return number < 10 ? "0" + number : number;
}
console.log(getFormattedDate(new Date("2019-08-02T05:01:03Z")));
Use the following script to get the current date and time using JavaScript in “Y-m-d H:i:s” format
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date+' '+time;
console.log(dateTime);

Parse date in javascript issues

I get such date in javascript
var val = "1960-05-15T20:00:00"
But if I do
var date = new Date(val);
The data I get is one day later:
1960-05-16 // I use this to obtain it: Ext.Date.format(new Date(val), 'm/d/Y')
Can you help me how to parse this date? and get correct date with 1960-05-15?
Your date format is ISO 8601 represented as the local time with an offset to UTC appended.
The Ext.Date singleton support this format with the c flag.
var parsedDate = Ext.Date.parse('1960-05-15T20:00:00', 'c');
var dateStr = Ext.Date.format(parsedDate, 'Y-m-d');
// "1960-05-15"
Have a look at the Sencha ExtJs 6.2.1 documentation Ext.Date for further informations.
You can use native JS to accomplish the output of the Date object in to this format yyyy-mm-dd
Like so:
var val = '1960-05-15T20:00:00';
var d = new Date(val);
var date = d.getFullYear() + '-' + ('0' + (d.getMonth() + 1)).slice(-2) + '-' + ('0' + d.getDate()).slice(-2);
console.log(date);
When you do
var a = new Date(someDate)
variable a contains date according to your local timezone.
If you want date in same format as you entered , use toISOString method
var a = (new Date(someDate)).toISOString()
My recommendation would be, you can only assume the timezone from where the date is coming from. If you know exactly where that date is coming from, a.k.a London, New York, Sidney, etc... then you can use momentjs to set the UTC offset
var val = "1960-05-15T20:00:00"
// these are equivalent
moment(val).utcOffset("+08:00");
moment(val).utcOffset(8);
moment(val).utcOffset(480);
So the OP has said they're in
Tbilisi, Georgia GMT + 4.00
so
moment(val).utcOffset("+04:00");

Date.UTC() gets value null

From Server I get Date in UTC format like ,
2016-04-13T02:37:13.211316121-04:00
When I use this to display using new Date(data.Created_at) I get 7 min time difference. Like as I am displaying my date in format {{my_date | date: 'h:mm a'}}, insted showing 12:05 PM, it dispalys 11:58 AM. So I tried this,
data.Created_at = new Date(Date.UTC(data.Created_at))
which returns null value. Is there any problem in my code? How should I get perfect date?
If you check syntax of Date.UTC,
Date.UTC(year, month[, day[, hour[, minute[, second[, millisecond]]]]])
It expects value in different variables and not in date string. You can split it and manually parse it.
You can try something like this:
JSFiddle
var d = "2016-04-13T02:37:13.211316121-04:00";
var date_arr = d.split(/[-|T|\.|:]/);
var o = new Date(Date.UTC(date_arr[0], date_arr[1], date_arr[2], date_arr[3], date_arr[4], date_arr[5]));
console.log(date_arr, o);
Also, it gives me 8:07 AM, considering the time is 2:37 and my timezone is +5:30.
Use it like this
Date.UTC(year,month,day,hours,minutes,seconds,millisec)
The code you are using is invalid way to handle date. You can use this code
new Date('2016-04-13T02:37:13.211316121-04:00').toISOString();
var created_at = new Date(createdAt);
var created_at_date = (created_at.getUTCMonth()+1) + "/" + created_at.getUTCDate() + "/" + created_at.getUTCFullYear() + "/" + created_at.getHours() + ":"
+ created_at.getMinutes() + ":" + created_at.getSeconds();
Hope this will work for you!!!

pre-populating date input field with Javascript

I am trying to prepopulate a date into an html "date" input field, but it ignores the values I try to pass:
<html>
...
<input id='date' type='date'>
...
</html>
<script>
...
var myDate = new Date();
$("#date").val(myDate);
...
I have also tried passing the date object as a string
var myDate = new Date().toDateString();
$("#date").val(myDate);
When I open the form, the date field is blank. If I eliminate the type="date" tag, the value shows up as a string, but then I don't have access to the datepicker. How do I pre-populate a date input and still have use of the datepicker? I'm stumped.
Thanks.
It must be set in ISO-format.
(function () {
var date = new Date().toISOString().substring(0, 10),
field = document.querySelector('#date');
field.value = date;
console.log(field.value);
})()
http://jsfiddle.net/GZ46K/
Why Not to Use toISOString()
The <input type='date'> field takes a value in ISO8601 format (reference), but you should not use the Date.prototype.toISOString() function for its value because, before outputting an ISO8601 string, it converts/represents the date/time to UTC standard time (read: changes the time zone) (reference). Unless you happen to be working in or want that time standard, you will introduce a bug where your date will sometimes, but not always, change.
Populate HTML5 Date Input from Date Object w/o Time Zone Change
The only reliable way to get a proper input value for <input type='date'> without messing with the time zone that I've seen is to manually use the date component getters. We pad each component according to the HTML date format specification (reference):
let d = new Date();
let datestring = d.getFullYear().toString().padStart(4, '0') + '-' + (d.getMonth()+1).toString().padStart(2, '0') + '-' + d.getDate().toString().padStart(2, '0');
document.getElementById('date').value = datestring;
/* Or if you want to use jQuery...
$('#date').val(datestring);
*/
<input id='date' type='date'>
Populate HTML5 Date & Time Fields from Date Object w/o Time Zone Change
This is beyond the scope of the original question, but for anyone wanting to populate both date & time HTML5 input fields from a Date object, here is what I came up with:
// Returns a 2-member array with date & time strings that can be provided to an
// HTML5 input form field of type date & time respectively. Format will be
// ['2020-12-15', '01:27:36'].
function getHTML5DateTimeStringsFromDate(d) {
// Date string
let ds = d.getFullYear().toString().padStart(4, '0') + '-' + (d.getMonth()+1).toString().padStart(2, '0') + '-' + d.getDate().toString().padStart(2, '0');
// Time string
let ts = d.getHours().toString().padStart(2, '0') + ':' + d.getMinutes().toString().padStart(2, '0') + ':' + d.getSeconds().toString().padStart(2, '0');
// Return them in array
return [ds, ts];
}
// Date object
let d = new Date();
// Get HTML5-ready value strings
let dstrings = getHTML5DateTimeStringsFromDate(d);
// Populate date & time field values
document.getElementById('date').value = dstrings[0]
document.getElementById('time').value = dstrings[1]
/* Or if you want to use jQuery...
$('#date').val(dstrings[0]);
$('#time').val(dstrings[1]);
*/
<input type='date' id='date'>
<input type='time' id='time' step="1">
Thank you j08691. That link was the answer.
To others struggling like me, when they say input is "yyyy-mm-dd" the MEAN it!
You MUST have 4 digits for the year.
You MUST have a dash and no spaces.
You MUST have 2 digits for day and month.
In my example myDate.getMonth for January would only return "1" (actually it returns "0" because for some reason javascript counts months from 0-11). To get this right I had to do the following:
var myDate, day, month, year, date;
myDate = new Date();
day = myDate.getDate();
if (day <10)
day = "0" + day;
month = myDate.getMonth() + 1;
if (month < 10)
month = "0" + month;
year = myDate.getYear();
date = year + "-" + month + "-" + day;
$("#date").val(date);
I hope this helps others not waste hours like I did testing this before October or before the 10th of the month! LOL
Here is an answer based on Robin Drexlers but in local time.
//Get the local date in ISO format
var date = new Date();
date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
var datestr = date.toISOString().substring(0, 10);
//Set the field value
var field = document.querySelector('#date');
field.value = datestr;
If it's a datetime field you're modifying (as opposed to just the date) don't forget to add the time T00:00, or change the substring to 16 characters for example:
//Get the local date and time in ISO format
var date = new Date();
date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
var datestr = date.toISOString().substring(0, 16);
//Set the field value
var field = document.querySelector('#datetime');
field.value = datestr;
This below code populates the local date . The accepted answer populates UTC date.
var date = new Date();
field = document.querySelector('#date-id');
var day = date.getDate();
if(day<10){ day="0"+day;}
var month = date.getMonth()+1;
if(month<10){ month="0"+month;}
field.value = date.getFullYear()+"-"+month+"-"+day;
I don't have the reputation points to comment on another answer, so I'll just add a new answer. And since I'm adding an answer, I'll give more details than I would've in a comment.
There's an easier way to zero pad than all of the juggling that everyone is doing here.
var date = new Date();
var month = ('0' + (date.getMonth() + 1)).slice(-2);
var day = ('0' + date.getDate()).slice(-2);
var year = date.getFullYear();
var htmlDate = year + '-' + month + '-' + day;
console.log("Date: " + htmlDate);
Today, the output would be
Date: 2020-01-07
The code is building a dynamic string by prepending a quoted zero, then taking the last 2 characters with slice(-2). This way, if the zero makes it 01, the last 2 are 01. If the zero makes it 011, then the last two are 11.
As for the month starting at zero silliness, you can also add 1 dynamically before prepending the zero and everything still works. You just have to do the math operation before turning it into a string.
As a side note, I've noticed that when you update a date field, you have to hide the field before setting the value and show it after setting. I don't do this often enough, so I have to re-struggle each time I need to deal with it. Hopefully this will help someone from the future.
waves to future people

Categories

Resources