How can i change date format in vue js template - javascript

This is the format i got
2019-01-08T11:11:00.000Z
This is the format i want
2019-01-08
How can i format date like that?
Note: I don't want moment package

Use the Date constructor to create the new date object from your date string. Then you can create the date in any custom format using this object. See the code below.
const input = "2019-01-08T11:11:00.000Z";
const dateObj = new Date(input);
const year = dateObj.getFullYear();
const month = (dateObj.getMonth()+1).toString().padStart(2, '0');
const date = dateObj.getDate().toString().padStart(2, '0');
const result = `${year}-${month}-${date}`;
console.log(result);

Related

How can I get the ISO format for date and time in javascript?

I have two separate fields of date and time:-
const date = 2020-12-10;
const time = 22:00;
expected output:-
2020-12-10T10:00:00Z
I'm following this approach but the time in coming wrong:-
const date = DateUtil.getFullDateString(this.state.date_value);
const time = moment(this.state.time_value, ['HH.mm']).format('hh:mm a');
const momentObj = moment(date + time, 'YYYY-MM-DD HH:mm');
const dateTime = momentObj.toISOString();
the output of time is coming 18:30:00 but need to have 10:00:00
2020-12-10T18:30:00Z
You could parse date and time one by one, then add time to date and finally format as you want.
const date = '2020-12-10';
const time = '22:00';
const momentDate = moment(date).utc().startOf('day'); // utc() to avoid the offset
console.log(momentDate);
const momentTime = moment(time, 'HHmm').format('HH:mm');
console.log(momentTime);
const resultTime = momentDate.add(momentTime);
console.log(resultTime);
// Format as you want
console.log(resultTime.format('LLL'));
console.log(resultTime.format('YYYY-MM-DDThh:mm:ss.SSSA[Z]'));
console.log(resultTime.toISOString());
<script src="https://momentjs.com/downloads/moment.js"></script>
See this in order to know how to manage the UTC offset.

How to compare current Hours with a hour string JavaScript

I have attribute string Time:"10:50" response in JavaScript.
How to compare only hour of string with hour of system.
E.g: if 10=10 then run code in function.
Please help. thanks
You should wrap the string into a date object and use the getHours() function on the date object. something like
//in the oldDate, pass the string as params to the date constructor
let oldDate = new Date("date string")
//construct this one without a parameter and it will use the system time
let systemDate = new Date()
if(oldDate.getHours() == systemDate.getHours())
But if you are quite certain that the response is of the form "10:50" then this will be the better option
let time = "10:50"
let h = parseInt(time.split(":")[0])
let systemDate = new Date()
if(h == systemDate.getHours())
Create a Date object: let dateTime = new Date();
Get the current hour: let hour = dateTime.getHours();
Compare it with your desired object.

Convert date and hours/minutes/seconds to correct format javascript

I got date in format '20190702' and hours/minutes/seconds in format '125657'
What is the easiest way to convert it to 07/02/2019, 12:56:57
const time = "125657";
const chuncks = str.match(/.{1,2}/g).join(":"); //12:56:57
What about date?
You can just use substr function to extract a part of string and then combine the parts to form new string
const time = "125657";
const date = "20190702";
const formattedTime = `${time.substr(0,2)}:${time.substr(2,2)}:${time.substr(4,2)}`
const formattedDate = `${date.substr(4,2)}/${date.substr(6,2)}/${date.substr(0,4)}`
console.log(`${formattedDate}, ${formattedTime}`)
The easiest is maybe this:
const time = "125657".replace(/(..?)(..)(..)/, "$1:$2:$3");
const date = "20190702".replace(/(....)(..)(..)/, "$2/$3/$1");
console.log(date, time);
The question mark in the first pattern could serve if the time string could have 5 digits instead of 6. If you are certain you always get 6 digits, you can leave it out.
You can use Moment.js to parse dates, it will accept most formats.
let momentDate = new moment.utc('20190702', 'YYYYMMDD');
console.log("Parsed date: ", momentDate);
let momentDateTime = new moment.utc('20190702125657', 'YYYYMMDDHHmmss');
console.log("Parsed date (with time): ", momentDateTime );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Use Moment.js
You provide pattern along with data.
Here, "hh" means "hours" in pattern.
"use strict";
const moment = require("moment");
console.log(moment("125652", "hhmmss").toDate());
Assuming fixed length input strings of decimal digits, you could do something like this:
const date = "20190702";
const time = "125657";
const formatted_date = date.replace(/(\d{4})(\d{2})(\d{2})/, "$3/$2/$1");
//const formatted_time = time.match(/\d{2}/g).join(":");
const formatted_time = time.replace(/(\d{2})(\d{2})(\d{2})/, "$1:$2:$3");
const formatted_date_time = `${formatted_date}, ${formatted_time}`;
console.log(formatted_date_time);
If the year was 2-digit, you could have used the same exact logic and just add a reverse, but since it's a different length, I advise you a manual composition:
const date = '20190702';
const chunks = date.match(/.{1,2}/g);
const formattedDate = [chunks[3], chunks[2], chunks[0]+chunks[1]].join('/');
console.log(formattedDate)
You may use moment.js library to format your date. In your case, the code may look like:
var time = '20190702,125657';
var formated_time = moment(time, "YYYYMMDD,HHmmss").format('DD/MM/YYYY,HH:mm:ss');

How to get Date String Format in JavaScript using moment or vanilla JavaScript?

So I have this sample date "2015-11-13T18:43:58.720Z" and I want to get the string format of it. I used moment to get the string format.
const d = '2015-11-13T18:43:58.720Z';
const format = moment(d).creationData().format;
// output is YYYY-MM-DDTHH:mm:ss.SSSSZ
But when I do something like
const a = moment(d).format('MM-DD-YYYY HH:mmA');
// output is 11-14-2015 02:43AM
const b = moment('11-14-2015 02:43AM', 'MM-DD-YYYY HH:mmA').format('YYYY-MM-DDTHH:mm:ss.SSSSZ');
// output is different 2015-11-14T02:43:00.0000+08:00
// expecting 2015-11-13T18:43:58.720Z
How can I get the proper string format of (2015-11-13T18:43:58.720Z) using moment or vanilla js when getting current timestamp?
You can do that in Vanilla JavaScript, without moment.js.
const newDate = new Date().toISOString();
console.log(newDate)
This converts the input into the date in ISO format (as a string).
More examples:
const newDate = new Date().toISOString();
const anotherDate = new Date('2015-11-13T18:43:58.720Z').toISOString();
const yetAnotherDate = new Date(2019, 3, 15, 10).toISOString();
console.log(newDate);
console.log(anotherDate);
console.log(yetAnotherDate);

I'm getting JavaScript error "d.getMonth is not a function" when trying to format a date using d3.time.format

I have a date value 2016-02-18 and I want to convert it to Feb 18.
I tried the following code, but it returns an error that get.month is not a function. I have also tried using format.parse(), but that didn't work either.
My code :
var dateLast = "2016-02-18";
var date = Date.parse(dateLast.replace(/-/g,"/"));
var format = d3.time.format("%b-%d");
var dateConvert = format(date);
console.log(dateConvert);
The error message :
TypeError: d.getMonth is not a function at d3_time_formats.b
(d3.js:2517) at format (d3.js:2431)
You need to pass Date object into format function (see documentation):
var dateLast = "2016-02-18";
var date = Date.parse(dateLast.replace(/-/g,"/"))
var format = d3.time.format("%b-%d");
var dateConvert = format(new Date(date))
console.log(dateConvert)
The D3.js way :
Using d3.time.format, the most efficient way to achieve what you're going for, is this :
var dateLast = "2016-02-18";
var format = d3.time.format("%b %d");
var dateConvert = format(new Date(dateLast));
alert(dateConvert); // Output : Feb 18
(See also this Fiddle)
So, basically, you don't need this dateLast.replace or Date.parse at all. You can just use your date string directly as input of new Date().
The vanilla JS way :
Personally, I wouldn't even use d3 (or any other library) at all to format dates. You can do it in vanilla JS with about the same amount of code :
var dateLast = "2016-02-18";
var format = { month : 'short', day : 'numeric' };
var dateConvert = new Date(dateLast).toLocaleDateString('en-US', format);
alert(dateConvert); // Output : Feb 18
(See also this Fiddle).

Categories