When used with .format('ll') I get a year, suffix, how can I fix the above to remove it?
E.g.: Jan 29, 2018 -> Jan 29
I try to use regular to replace, but it is quite complicated.
moment().format('ll').replace(new RegExp('[^\.]?' + moment().format('YYYY') + '.?'), '')
Jan 29, 2018 -> Jan 29,
reference: https://github.com/moment/moment/issues/3341
moment().format('ll')
.replace(moment().format('YYYY'), '') // remove year
.replace(/\s\s+/g, ' ')// remove double spaces, if any
.trim() // remove spaces from the start and the end
.replace(/[рг]\./, '') // remove year letter from RU/UK locales
.replace(/de$/, '') // remove year prefix from PT
.replace(/b\.$/, '') // remove year prefix from SE
.trim() // remove spaces from the start and the end
.replace(/,$/g, '')
Thanks: Localizing day and month in moment.js
How about using Javascript split :
console.log(moment().format('ll').split(',')[0]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
To remove the year and comma from the date string formatted with ll in moment.js, you can use the moment().format('MMM D') method, which will format the date in the format "MMM D" (e.g. "Jan 29"). Here's an example:
const moment = require('moment');
const date = moment().format('ll');
const formattedDate = moment(date, 'll').format('MMM D');
console.log(formattedDate); // Outputs e.g. "Feb 18"
In this example, we first format the date string using ll, and then use the format method with the MMM D format to extract only the month and day. The resulting string will not include the year or comma.
Alternatively, you can use the replace method with a regular expression to remove the year and comma from the date string:
const moment = require('moment');
const date = moment().format('ll');
const formattedDate = date.replace(/, \d{4}/, '');
console.log(formattedDate); // Outputs e.g. "Feb 18"
In this example, we use the replace method with a regular expression that matches a comma followed by a space and a four-digit year, and replace it with an empty string. This will remove the year and comma from the date string, leaving only the month and day.
Related
I have a date in a string format that looks like so:
"31/07/2022 16:00"
... and I want to change it to a valid Javascript date and time.
I've tried changing the forward slashes to '-' with this code:
let lala
let lalawood = '31/07/2022 16:00'
lala = lalawood.replace(/\//g, '-');
console.log(lala); // outputs 31-07-2022 16:00
but it returns '31-07-2022 16:00' which is still an invalid date time.
How can I convert this into a valid Date and Time so that I can use it to compare two dates programmatically?
The problem here is that you are using time in European format (DD/MM/YYYY), while JavaScript compiling it as American time format (MM/DD/YYYY),
Here is a snippet that switch days and months to create a valid date
let s = '31/07/2022 17:30';
s = s.replace(/[^0-9 ]/g, " ").split(' ');
let d = new Date(s[2], s[1]-1, s[0], s[3], s[4]);
console.log(d);
I have a requirement in my codebase where I need to trim the timestamp if it has a timezone on it.
An example of a timestamp I may receive:
"2017/08/23 12:00:00 Z"or "2017/08/23 12:00:00 +05:30"
My desired output should be:
"2017/08/23 12:00:00"or "2017/08/23 12:00:00"
You could do something like this:
var d1 = "2017/08/23 12:00:00 Z"
var d2 = "2017/08/23 12:00:00 +05:30"
var d3 = "2017/08/23 12:00:00"
const getDatePart = d => d.split(' ').reduce((r,c,i) => i <= 1 ? `${r} ${c}` : r)
console.log(getDatePart(d1))
console.log(getDatePart(d2))
console.log(getDatePart(d3))
It would do the job via String.split & reduce. It would cover the date strings with one ' ' between the date & time.
Use lastIndexOf method to find the last space and then substring to it.
var date = "2017/08/23 12:00:00 Z";
var date1 = "2017/08/23 12:00:00 +05:30";
console.log(date.substring(0, date.lastIndexOf(" ")));
console.log(date1.substring(0, date.lastIndexOf(" ")));
Assuming you process one datetime at a time, you can use this regex:
/(?<=\").*?(?:(?=Z)|(?=[+-]))/
It looks back to find a double quote, then matches any char zero or more times (non greedy), then it looks forward for either a 'Z' or plus [+] or minus [-].
I have a string that contains a datetime in the following format
2016-07-30 00:00:01.0310000
I need to convert this to a datetime object in JavaScript retaining the sub-seconds.
If I use
var d = new Date('2016-07-30 00:00:01.0310000');
Everything after 01 is dropped, how can I efficiently achieve this?
You'll have to parse the string yourself (which is quite simple, the only tricky bit is trailing zeros on the milliseconds value) and build the date using the Date(years, months, days, hours, minutes, seconds, milliseconds) constructor. Or use a library and a format string.
Here's an example:
var str = "2016-07-30 00:00:01.0310000";
var parts = /^\s*(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})\.(\d+)\s*$/.exec(str);
var dt = !parts ? null : new Date(
+parts[1], // Years
+parts[2] - 1, // Months (note we start with 0)
+parts[3], // Days
+parts[4], // Hours
+parts[5], // Minutes
+parts[6], // Seconds
+parts[7].replace(/0+$/, '') // Milliseconds, dropping trailing 0's
);
if (dt.toISOString) {
console.log(dt.toISOString());
} else {
console.log("date", dt.toString());
console.log("milliseconds", dt.getMilliseconds());
}
In the regex, \d means "a digit" and {x} means "repeated x times".
The !parts ? null : new Date(...) bit is so that if the string doesn't match the format, we get null rather than an error.
The milliseconds are saved (31), but what comes after that is not saved, because javascript does not support it.
You could use library like Moment JS, You can read more http://momentjs.com/docs/
var day = moment("2016-07-30 00:00:01.0310000");
console.log(day._d); // Sat Jul 30 2016 00:00:01 GMT+0100 (WAT)
How can I convert a string representation of a date to a real javascript date object?
the date has the following format
E MMM dd HH:mm:ss Z yyyy
e.g.
Sat Jun 30 00:00:00 CEST 2012
Thanks in advance
EDIT:
My working solution is based on the accepted answer. To get it work in IE8, you have to replace the month part (e.g. Jun) with the months number (e.g. 5 for June, because January is 0)
Your date string can mostly be parsed as is but CEST isn't a valid time zone in ISO 8601, so you'll have to manually replace it with +0200.
A simple solution thus might be :
var str = "Sat Jun 30 00:00:00 CEST 2012";
str = str.replace(/CEST/, '+0200');
var date = new Date(str);
If you want to support other time zones defined by their names, you'll have to find their possible values and the relevant offset. You can register them in a map :
var replacements = {
"ACDT": "+1030",
"CEST": "+0200",
...
};
for (var key in replacements) str = str.replace(key, replacements[key]);
var date = new Date(str);
This might be a good list of time zone abbreviation.
You can use following code to convert string into datetime:
var sDate = "01/09/2013 01:10:59";
var dateArray = sDate.split('/');
var day = dateArray[1];
// Attention! JavaScript consider months in the range 0 - 11
var month = dateArray[0] - 1;
var year = dateArray[2].split(' ')[0];
var hour = (dateArray[2].split(' ')[1]).split(':')[0];
var minute = (dateArray[2].split(' ')[1]).split(':')[1];
var objDt = new Date(year, month, day, hour, minute);
alert(objDt);
I have a string formatted as either
Today 3:28AM
Yesterday 3:28AM
08/22/2011 3:28AM
What I need to do is somehow extract into a variable the date portion of my string, ie. 'Today', 'Yesterday' or a date formatted as DD/MM/YYYY.
Is something like this possible at all with Javascript?
Since the JavaScript date parser won't recognize your dates, you can write a parser that puts the date into a format that it will recognize. Here is a function that takes the date examples that you gave and formats them to get a valid date string:
function strToDate(dateStr) {
var dayTimeSplit = dateStr.split(" ");
var day = dayTimeSplit[0];
var time = dayTimeSplit[1];
if (day == "Today") {
day = new Date();
} else if (day == "Yesterday") {
day = new Date();
day.setDate(day.getDate() - 1);
} else {
day = new Date(day);
}
var hourMinutes = time.substring(0, time.length -2);
var amPM = time.substring(time.length -2, time.length);
return new Date((day.getMonth() + 1) + "/" + day.getDate() + "/" + day.getFullYear()
+ " " + hourMinutes + " " + amPM);
}
Then you can call stroToDate to convert your date formats to a valid JavaScript Date:
console.log(strToDate("Today 3:28AM"));
console.log(strToDate("Yesterday 3:28AM"));
console.log(strToDate("08/22/2011 3:28AM"));
Outputs:
Sun Sep 25 2011 03:28:00 GMT-0700 (Pacific Daylight Time)
Sat Sep 24 2011 03:28:00 GMT-0700 (Pacific Daylight Time)
Mon Aug 22 2011 03:28:00 GMT-0700 (Pacific Daylight Time)
Obviously "Today" and "Yesterday" can never be transformed back to a real numeric date, for now it seems that what are you trying to do here is to save it as "Today" and "Yesterday", right?
It appears that the dd/mm/yyyy hh:mmxx you specified is always separated by a space.
so you can just split the string into two, and save the first part as your date.
the javascript function:
http://www.w3schools.com/jsref/jsref_split.asp
As for how to transform from "Today" back to 26/09/2011 etc, you need to seek solution from the XML side.
Here is a similar question: Javascript equivalent of php's strtotime()?
Here is the linked article: http://w3schools.com/jS/js_obj_date.asp
And the suggested solution:
Basically, you can use the date constructor to parse a date
var d=new Date("October 13, 1975 11:13:00");
There are a couple of ways you could do this. I will offer 2 of them.
option1:
If the day always at the beginning of the string you could capture the the first part by using a regular expression like /([a-z0-9]*)\s|([0-9]{1,})\/([0-9]{1,})\/([0-9]{1,})\s/ <- im not the best regex writer.
option2:
You could also do a positive look ahead if the time come immediately after the day (like your example above. Here is a link with the proper syntax for JS regex. http://www.javascriptkit.com/javatutors/redev2.shtml you can scroll down to lookaheads and see an example that should get you suared away there.
var reTYD = /(today|yesterday|\d{1,2}\/\d{1,2}\/\d{4})/i;
console.log( myString.match(reTYD) );