Unable to convert data '19-10-2002' into date - javascript

I need to pass a date parameter in format (dd-MM-yyyy) and convert in this format (yyyy-MM-dd) to send API.
So I do this:
convert(date:string){
date //is in the format(dd-MM-yyyy)
date =formatDate(date , "yyyy-MM-dd", 'en_US');
and I obtain this error:
Unable to convert "19-10-2002" into a date
Anyone can help me?

You could just do
console.log(
"19-10-2002".split('-').reverse().join('-')
)

If you want to pass a string to "formatDate" it has to be in "ISO date-time" format (the complete format is "YYYY-MM-DDThh:mm:ss.sTZD", but you can drop any part from the end and use like "YYYY" or "YYYY-MM-DD"). so the string you are passing to it is not recognized as a valid input date.
so you can use Dave's code

Here is the custom date formatter function which accepts date, format and separator/delimiter to convert the passed date with passed format.
function dateFormatter(date, format, delimiter) {
const dateItems = date.split(delimiter)
const formatItems = format.toLowerCase().split(delimiter);
const day = formatItems.indexOf('dd');
const month = formatItems.indexOf('mm');
const year = formatItems.indexOf('yyyy');
const formattedDate = ([dateItems[day], dateItems[month], dateItems[year]]).join(delimiter)
console.log(formattedDate)
return formattedDate
}
// run example
dateFormatter('02-03-2020', 'YYYY-MM-DD', '-');
dateFormatter('02/03/2020', 'MM/DD/YYYY', '/');

Related

Convert given timestamp to influxdb timestamp

My Incoming Date is in format : 15.08.2017 23:03:23.120000
Here I am using Node-Red Platform to convert msg.payload.time in Influx timestamp but I am getting this Error:
"Error: Expected numeric value for, timestamp, but got '15.08.2017 23:03:23.120000'!".
Please let me know the script for given timestamp to influxdb timestamp.
InfluxDB expects unix timestamps and msg.payload.time might be a string, hence you are getting the error.
In order to generate a timeStamp from a date, you can use the Date functionality of JS.
It works in the following way:
new Date('<your-date-string>').valueOf()
Here the date-string is expected in 'YYYY-MM-DD hh:mm:ssZ' format.
In your case, since the msg.payload.time is available in dd.mm.yy hh:mm:ssZ format, you will need to perform some additional operations.
You can update your code as below:
const incomingDate = msg.payload.time;
// extract the date dd.mm.yyyy from the incoming Date String
const splittedDate = incomingDate.split(' ');
// Convert the date from dd.mm.yyyy to yyyy-mm-dd format
let date = splittedDate[0].split('.').reverse().join('-');
// Store time value in a separate variable for later use.
const time = splittedDate[1];
// merge date and time to form yyyy-mm-dd hh:mm:ssZ format
const datetime = `${date} ${time}`
// assign the timestamp value to fields.time
fields.time = new Date(datetime).valueOf();
Here is a working example
const incomingDate = '15.08.2017 23:03:23.120000';
const splittedDate = incomingDate.split(' ');
let date = splittedDate[0].split('.').reverse().join('-');
const time = splittedDate[1];
const datetime = `${date} ${time}`
console.log(datetime);
console.log(new Date(datetime).valueOf())

From date to date validation using javascript

I want to validate from and to date. my date format is d/m/Y H:i
Here is my code:
var startDate = new Date($('#fromdate').val());
var endDate = new Date($('#todate').val());
if (endDate.getTime() <= startDate.getTime()) {
return [false,"To Date cannot be less than From Date"];
}else{
return [true,""];
}
result showing 'Invalid Date'.
Here the date format is different. How to change the date format before passing to Date function?.
You can parse the date string on your own or you can use an external library, like dayjs or momentjs
A simple parsing function could be something like this (assuming the format is the one you mentioned in your question):
function getDateFromCustomFormat(dateString) {
const dateFormatPattern = /^([0-9]{2})\/([0-9]{2})\/([0-9]{4}) ([0-9]{2}):([0-9]{2})$/
const parts = dateString.match(dateFormatPattern)
console.log(parts)
const validFormatString = `${parts[3]}-${parts[2]}-${parts[1]} ${parts[4]}:${parts[5]}`
new Date(validFormatString)
}

Convert date format 27.05.2015 01:46:32.UTC to Locale time

Can anyone help me to convert date format 27.05.2015 01:46:32.UTC to Locale time.
I tried the following code
var date = new Date('27.05.2015 01:46:32.UTC ');
date.toString();
This is also not working.
Even momentjs is also gives error to convert this format of date.
As per statement even momentjs is also gives error to convert this format of date, I have taken liberty and used momentjs here.
You need to use string-format moment constructor to pass string and format in which input string is.
Use
var t = "27.05.2015 01:46:32.UTC";
//pass dateTime string and its format, it will return
//moment object
var cdt = moment.utc(t, 'DD.MM.YYYY HH:mm:ss');
//Get date object
var date = cdt.toDate();
//Use date variable as per requiremnt
alert(date);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.js"></script>
The format you are using for Date is DD.MM.YYYY. So you have to change this to MM.DD.YYYY for a valid java script object.
var date = '27.05.2015 01:46:32.UTC';
var date1 = date.split(' ');
console.log(date1)
var date2 = date1[0].split('.');
console.log(date2)
var date3 = date2[1]+ '.' +date2[0] +'.'+ date2[2];
console.log(date3)
var final_date = date3 + ' ' + date1[1];
console.log(final_date);
final_date.toString();

Formatting date in ExtJs

I am working with ExtJS and want to use Ext.Date.format(value,format). I have date as 2014/03/05. How can I convert this to the date object so that it can be passed as 'value' argument to the format() function?
You can try this :
var dt = new Date('2014/03/05');
And you do this to format your date Ext.Date.format(dt,'d-m-Y'); or whatever format you want. :)
You can parses date:
var dt = Ext.Date.parse("2014/03/05", "Y/m/d");
Then you can format it another format:
var td = Ext.Date.format(dt,'d-m-Y');

moment js extract year from string

I'm new to moment.js and I can't really understand the documentation. I'd like to manipulate some dates in string format.
I have my date as string from json feed and looks like:
var year = item.date
// it returns a string like "25/04/2012"
How do I extract the year from it using moment.js ?
You can use
moment("25/04/2012","DD/MM/YYYY").format("YYYY")
or
moment("25/04/2012","DD/MM/YYYY").year()
in your example:
moment(item.date,"DD/MM/YYYY").year()
Or you can convert the string to date then extract the year:
var date = new Date(dateString);
if (!isNaN(date)) {
return date.getFullYear();
}

Categories

Resources