Convert Round-Trip Time Pattern in ES6 - javascript

I'm trying to convert something like this 2020-10-01T17:00:00.000Z to the correct time something like 06:00:00 PM. Pls see my code below:
const date = "2020-10-01T17:00:00.000Z";
const output = new Date(date).toLocaleTimeString('en-US');
console.log(output);

If you specifically need the time to be in UTC (instead of the local user's timezone), then I think you would need to build your own formatter function to do it, e.g.:
function formatDate(str, includeDate){
const date = new Date(str);
const hours = date.getUTCHours();
let twoDigits = (no) => {
const str = no.toString();
return (str.length === 1 ? '0' + str : str);
};
let strdate = (includeDate ? twoDigits(date.getUTCMonth() + 1) + '/' + twoDigits(date.getUTCDate()) + '/' + twoDigits(date.getUTCFullYear()) + ' ' : '');
if(12 <= hours) {
return strdate + twoDigits(hours === 12 ? 12 : hours - 12) + ':' + twoDigits(date.getUTCMinutes()) + ':' + twoDigits(date.getUTCSeconds()) + ' PM';
} else {
return strdate + twoDigits(hours) + ':' + twoDigits(date.getUTCMinutes()) + ':' + twoDigits(date.getUTCSeconds()) + ' AM';
};
};
console.log(formatDate("2020-10-01T17:00:00.000Z", true));
Here, you are constructing the time string from individual UTC segments. You could alternatively parse the input string using a regex, get the number of hours and then build the string that way.
Edit: updated to optionally also include the date, in US format mm/dd/yyyy.

Related

Convert Current date in IST format using Javascript

I want to convert current date value to the below format using javascript
2019-08-23T08:23:47+0530
I had tried the following code
var currentTime = new Date();
var currentOffset = currentTime.getTimezoneOffset();
var ISTOffset = 330; // IST offset UTC +5:30
var ISTTime = new Date(currentTime.getTime() + (ISTOffset + currentOffset)*60000);
and also try to convert to toUTCString(). But any of them gives the desired format.
try this it will work for ISO date
Date.prototype.toIsoString = function() {
var timezone = -this.getTimezoneOffset(),
DF = timezone >= 0 ? '+' : '-',
pad = function(nm) {
var narmal = Math.floor(Math.abs(nm));
return (narmal < 10 ? '0' : '') + narmal;
};
return this.getFullYear() +
'-' + pad(this.getMonth() + 1) +
'-' + pad(this.getDate()) +
'T' + pad(this.getHours()) +
':' + pad(this.getMinutes()) +
':' + pad(this.getSeconds()) +
DF + pad(timezone / 60) +
'' + pad(timezone % 60);
}
var date = new Date();
alert(date.toIsoString())

How to convert a number to time?

I'm trying to create a function that takes a number and returns a timestamp (HH:mm) using date-fns version 1.30.1 or plain JavaScript.
What I'm trying to achieve is to help a user when entering a time. I'm using Vue.js to update the field when a user moves away from the input field. So if a user types 21 then moves away, the field would ideally update to 21:00.
Some examples would be:
21 = 21:00
1 = 01:00
24 = 00:00
2115 = 21:15
Numbers like 815 does not have to return 08:15. Numbers like 7889 should return an error.
I have tried using regex:
time = time
.replace(/^([1-9])$/, '0$1')
.replace(/^([0-9]{2})([0-9]+)$/, '$1:$2')
.replace(/^24/, '00:00')
I have also tried using the parse method in date-fns but can't seem to wrap my head around how to solve this.
Version 1, converting anything less than 100 to hours
const num2time = num => {
if (num < 100) num *=100;
const [_,hh,mm] = num.toString().match(/(\d{1,2})(\d{2})$/)
return `${hh.padStart(2,"0")}:${mm}`
}
console.log(num2time(8));
console.log(num2time(2115));
console.log(num2time(15));
console.log(num2time("8"));
console.log(num2time("2115"));
version 2 can be used if the digits are always representing valid (h)hmm
const num2time = num => num.toString().replace(/(\d{1,2})(\d{2})$/,"$1:$2");
console.log(num2time(815));
console.log(num2time(2115));
console.log(num2time("2115"));
Conversion based on <100 (hours-only) and >=100 (100*hours+minutes), plus some fight with 24 and single-digit numbers (both hours and minutes):
function num2time(num){
var h,m="00";
if(num<100)
h=num;
else {
h=Math.floor(num/100);
m=("0"+(num%100)).slice(-2);
}
h=h%24;
return ("0"+h).slice(-2)+":"+m;
}
console.log(num2time(8));
console.log(num2time(801));
console.log(num2time(24));
console.log(num2time(2401));
console.log(num2time(2115));
console.log(num2time("8"));
console.log(num2time("2115"));
Original answer, kept for the comment only, but would not handle 24 or single-digit minutes correctly:
For example you can do a very mechanical conversion
function num2time(num){
if(num<10)
t="0"+num+":00";
else if(num<100)
t=num+":00";
else {
if(num<1000)
t="0"+Math.floor(num/100);
else if(num<2400)
t=Math.floor(num/100)
else
t="00";
t+=":"+(num%100);
}
return t;
}
console.log(num2time(8));
console.log(num2time(2115));
console.log(num2time("8"));
console.log(num2time("2115"));
Example verification:
function num2time(num){
var h,m="00";
if(num<100)
h=num;
else {
h=Math.floor(num/100);
m=("0"+(num%100)).slice(-2);
}
if(h<0 || h>24) throw "Hour must be between 0 and 24"
if(m<0 || m>59) throw "Minute must be between 0 and 59"
h=h%24;
return ("0"+h).slice(-2)+":"+m;
}
var numstr=prompt("Enter time code");
while(true) {
try {
console.log(num2time(numstr));
break;
} catch(ex) {
numstr=prompt("Enter time code, "+numstr+" is not valid\n"+ex);
}
}
You can use the first char as hour and last char as minute, you've to pad 0 on when there is less than 4 chars.
When there is 1 or 0 char you need to pad both left and right.
When there is 2 or 3 char you only pad right.
time_str = '230'
date = new Date('1970-01-01T' + time_str.slice(0,2).padStart(2,"0") + ':' + time_str.slice(2,4).padEnd(2,"0") + 'Z');
console.log(date)
console.log(("0" + date.getUTCHours()).slice(-2) + ":" + ("0" + date.getUTCMinutes()).slice(-2))
time_str = '24'
date = new Date('1970-01-01T' + time_str.slice(0,2).padStart(2,"0") + ':' + time_str.slice(2,4).padEnd(2,"0") + 'Z');
console.log(date)
console.log(("0" + date.getUTCHours()).slice(-2) + ":" + ("0" + date.getUTCMinutes()).slice(-2))
time_str = '3'
date = new Date('1970-01-01T' + time_str.slice(0,2).padStart(2,"0") + ':' + time_str.slice(2,4).padEnd(2,"0") + 'Z');
console.log(date)
console.log(("0" + date.getUTCHours()).slice(-2) + ":" + ("0" + date.getUTCMinutes()).slice(-2))
time_str = '78'
date = new Date('1970-01-01T' + time_str.slice(0,2).padStart(2,"0") + ':' + time_str.slice(2,4).padEnd(2,"0") + 'Z');
console.log(date)
console.log(("0" + date.getUTCHours()).slice(-2) + ":" + ("0" + date.getUTCMinutes()).slice(-2))
DateFns implementation
IMHO, working on adding and removing minutes and hours is a cleaner way to manage this transform:
function formattedTime(val) {
let helperDate;
if(val.length <= 2) {
if(val > 24)return 'error';
helperDate = dateFns.addHours(new Date(0), val-1);
return dateFns.format(helperDate, 'HH:mm');
}
if(val.length > 2) {
let hhmm = val.match(/.{1,2}/g);
if(hhmm[0] > 24 || hhmm[1] > 60) return 'error';
helperDate = dateFns.addHours(new Date(0), hhmm[0]-1);
helperDate = dateFns.addMinutes(helperDate, hhmm[1]);
return dateFns.format(helperDate, 'HH:mm');
}
}
const myArr = [21, 1, 24, 2115, 815];
myArr.forEach(
val => console.log(formattedTime(val.toString()))
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.min.js"></script>

using date in javascript

I have trouble using date in Javascript, in PHP you use something like date("Y-m-d H:i s") to retrieve the specific date and time, how can I achieve this in Javascript? the getMonth() method only returns 1 digit, I really need them to be in 2 digits
Since I made comments on almost all answers, I'd better post my suggestion
DEMO
function pad(num) { return ("0"+num).slice(-2); }
function getDisplayDate() {
var date = new Date();
return date.getFullYear()+
"-"+pad(date.getMonth()+1)+
"-"+pad(date.getDate())+
" "+pad(date.getHours())+
":"+pad(date.getMinutes())+
":"+pad(date.getSeconds());
}
setInterval(function() {
document.getElementById("time").innerHTML=getDisplayDate();
},500);
why dont you add 0 before when you get <10
Try this :
function dateToYMD(date) {
var d = date.getDate();
var m = date.getMonth() + 1;
var y = date.getFullYear();
return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d) + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
}
var d = new Date();
alert(dateToYMD(d));
This code is adjusted based on the pointers given by #mplungjan -- (credits to him please)
Also check out his solution, which is a better one for use with date digits.
var str = 10; // month-digit from getMonth()
function pad(val) {
return "0" + val;
}
var month = str < 10 ? pad(str) : str;
console.log(month);
you can year, minutes, etc from Date class. You can get 2 digits month using some trick like example below. e.g
Date.prototype.getLongMonth = function() {
var month = this.getMonth();
if (String(month).length == 1) month = '0'.concat(month);
return month;
}
var now = new Date();
var theDate = now.getFullYear() + '-' + now.getLongMonth() + '-' + now.getDate() + ' ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
console.log(theDate); // result : 2013-02-17 12:41:2

Parsing the date in MM/DD/YY format

I get the response for the Date in this format while showing in the text box, how do i covert it to MM/DD/YYYY and Again re covert it to back to this format while sending
/Date(1306348200000)/
function dateToString(date) {
return (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getYear();
}
function dateFromString(str) {
return new Date(str);
}
Note, that month begins from 0.
To convert the regExp-like string to a real Date Object you could use:
var dateNum = Number('/Date(1306348200000)/'.replace(/[^0-9]/g,''))
, dat = new Date(dateNum); //=>Date {Wed May 25 2011 20:30:00 GMT+0200}
To display formatted dates I use my own small library, which may be of use to you.
var s = '/Date(1306348200000)/';
// convert to javascript date
var date = new Date(parseInt(s.substr(6, 13))); // removes /Date( & )/
// format the date
function pad(n) { return n < 10 ? '0' + n : n; } // leading zeros
var ddmmyy = pad(date.getDate()) + '/' + pad(date.getMonth() + 1) + '/' + date.getFullYear().toString().substr(2);
// convert back
s = '/Date(' + date.getTime() + ')/';
here you can find everything regarding javascript dates http://www.w3schools.com/js/js_obj_date.asp

How to get correct gmt time in Javascript

For using the Amazon mechanical turk API I want to get the current GMT time and show it in ISO format
2011-02-24T20:38:34Z
I am wondering if there is any way to correctly get the gmt time and also be able to reformat it with ISO format. I can use something like now.toGMTString(); but it makes a string out of the date and it is hard to reformat it with ISO.
var year = now.getUTCFullYear()
var month = now.getUTCMonth()
var day= now.getUTCDay()
var hour= now.getUTCHours()
var mins= now.getUTCMinutes()
var secs= now.getUTCSeconds()
var dateString = year + "-" + month + "-" + day + "T" + hour + ":" + mins + ":" + secs + "Z"
You should be using UTC now instead of GMT. (Amounts to almost the same thing now, and it is the new standard anyway)
I believe this will work for you:
Number.prototype.pad = function(width,chr){
chr = chr || '0';
var result = this;
for (var a = 0; a < width; a++)
result = chr + result;
return result.slice(-width);
}
Date.prototype.toISOString = function(){
return this.getUTCFullYear().pad(4) + '-'
+ this.getUTCMonth().pad(2) + '-'
+ this.getUTCDay().pad(2) + 'T'
+ this.getUTCHours().pad(2) + ':'
+ this.getUTCMinutes().pad(2) + ':'
+ this.getUTCSeconds().pad(2) + 'Z';
}
Usage:
var d = new Date;
alert('ISO Format: '+d.toISOString());
Not much more different than every else's answer, but make it built-in to the date object for convenience
function pad(num) {
return ("0" + num).slice(-2);
}
function formatDate(d) {
return [d.getUTCFullYear(),
pad(d.getUTCMonth() + 1),
pad(d.getUTCDate())].join("-") + "T" +
[pad(d.getUTCHours()),
pad(d.getUTCMinutes()),
pad(d.getUTCSeconds())].join(":") + "Z";
}
formatDate(new Date());
Output:
"2011-02-24T21:01:55Z"
This script can take care of it
/* use a function for the exact format desired... */
function ISODateString(d){
function pad(n){return n<10 ? '0'+n : n}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'}
var d = new Date();
document.write(ISODateString(d)); // prints something like 2009-09-28T19:03:12Z

Categories

Resources