moment js extract year from string - javascript

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();
}

Related

Why 1 day off when I try to convert date into toisostring in javascript?

I am trying to convert date object to ISOString() formate. But it return me 1 day off ( I mean it reduce 1 day ).
var fromDate = {
day:4,
month:5,
year:2012
}
var fromDateString = new Date(fromDate.year+'-'+fromDate.month+'-'+fromDate.day)
console.log(fromDateString.toISOString())
It is because of timezone, new Date() is in your current timezone, toISOString() is using standard timezone.
I have searched and I find best solution for every date object to convert in any format.
Comment if you agree?
var dateObj = {
day:2,
month:5,
year:2012
}
var date = new Date;
date.setFullYear(dateObj.year,dateObj.month-1,dateObj.day)
console.log(date)

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

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', '/');

How to parse a date like '2009-09-13' in D3.JS or moment

I have several dates as strings that are in the format: YYYY-MM-DD. So for example:
var origDate = '2009-09-13'
I want to parse them so that they're just written out as month (abbreviated or full month), day, year like: Sept. 9, 2009
..Is there a way to do this in D3.JS or Moment.JS?
Right now I'm using this D3 formula to parse the dates:
var format = d3.time.format("%Y-%m-%d").parse;
But when I do: format(origDate),
I get really long dates like:
Is there a way to do this in D3.JS?
Yes. Your line
var format = d3.time.format("%Y-%m-%d").parse;
is creating a date object. You need to apply formatting to the object to get the desired output string:
// working date:
var string = '2009-05-01';
// set up a format
var format = d3.time.format("%Y-%m-%d");
// convert the date string into a date object:
var date = format.parse(string);
// output the date object as a string based on the format:
console.log(format(date));
// use the desired format
var format1 = d3.time.format("%B %d, %Y");
// output a date as a string in the desired format
console.log(format1(date));
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
Using moment do it like this:
var origDate = '2009-09-13'
mDate = moment(origDate);
console.log(mDate.format("DD/MM/YYYY"));
https://jsfiddle.net/0p2c6zjo/
Vanilla JS
Use the new Date constructor on your string (it is in a supported format), and then use a format function to map each month to its abbreviation and include other information.
var abbr = 'Jan. Feb. Mar. Apr. May June July Aug. Sept. Oct. Nov. Dec.'.split(' ')
function format (date) {
return abbr[date.getUTCMonth()] + ' ' + date.getUTCDate() + ', ' + date.getUTCFullYear()
}
var origDate = '2009-09-13'
console.log(
format(new Date(origDate))
)
Moment.js
Moment.js objects have a format function that takes a format string. For the full list of parameters you can use, see the documentation on displaying.
var origDate = '2009-09-13'
console.log(
moment.utc(origDate).format('MMM. D, YYYY')
)
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.js"></script>

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();

String date to javascript date: Parse date [duplicate]

This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Closed 3 years ago.
I want to parse dates (string date format to javascript date format), but I have various string date format like YYYY-MM-DD, DD-MM-YYYY and 'DD/MM/YYYY' and so..
Is there any generic procedure or way to convent from these string date format to javascript date format?
These are two libraries that I use for that:
moment.js
datejs
Here userFormat string could be in these format 'DD-MM-YYYY', 'YYYY-MM-DD', 'DD/MM/YYYY' etc..
function parseDate(dateString, userFormat) {
var delimiter, theFormat, theDate, month, date, year;
// Set default format if userFormat is not provided
userFormat = userFormat || 'yyyy-mm-dd';
// Find custom delimiter by excluding
// month, day and year characters
delimiter = /[^dmy]/.exec(userFormat)[0];
// Create an array with month, day and year
// so we know the format order by index
theFormat = userFormat.split(delimiter);
//Create an array of dateString.
theDate = dateString.split(delimiter);
for (var i = 0, len = theDate.length; i < len; i++){
//assigning values for date, month and year based on theFormat array.
if (/d/.test(theFormat[i])){
date = theDate[i];
}
else if (/m/.test(theFormat[i])){
month = parseInt(theDate[i], 10) - 1;
}
else if (/y/.test(theFormat[i])){
year = theDate[i];
}
}
return (new Date(year, month, date));
}
Just go get datejs.
http://www.datejs.com/
...and never bother with writing your own Javascript date functions again.
function dateParsing(toDate, dateFormat) {
var dt = Date.parseInvariant(todate, dateFormat); // pass date and your desired format e.g yyyy/M/dd
alert(dt); // to check date
}

Categories

Resources