How to trim stamp string value - javascript

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 [-].

Related

momentjs get localized format with month and days only

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.

How to split Suffix from a number using jquery?

How can I convert this: NIFTY 16th JAN 12300 CE into NIFTY 16<sup>th</sup> JAN 12300 CE using jQuery?
To achieve this you can use a regular expression. To help negate the possibility of a false positive when the target string occurs within a word you can have the regex look specifically for the st, nd, rd or th strings when they follow an integer of 1 or 2 characters in length. Try this:
["NIFTY 16th JAN 12300 CE", "rd ND 21st April"].forEach(v => {
let output = v.replace(/(\d{1,2})(st|nd|rd|th)/gi, '$1<sup>$2</sup>');
console.log(output);
});
You can split th and rejoin with <sup>th</sup>
var x = "NIFTY 16th JAN 12300 CE";
var y = x.split("th").join("<sup>th</sup>");
console.log(y);
Here is the working code for the given requirement.
It works by identifying the day number, day suffix and replacing the pattern with required one.
var input = "NIFTY 16th JAN 12300 CE";
// Get the day string (Examples: 16th / 3rd)
var dayString = input.match(/[0-9]+[a-zA-Z]+/g);
// Get the day-number and day-suffix
var dayNumber = dayString.toString().match(/[0-9]+/i);
var daySuffix = dayString.toString().match(/[a-zA-Z]+/i);
// Print the output
console.log(dayNumber + "<sup>" + daySuffix + "</sup>");

Removing time from a javascript variable that holds data and time

I have a query that reads a date like this
var getstatusdate = $('#statusdate').val();
getstatusdate = "6/14/2016 12:00:00 AM"
Need to compare with another variable that stores date in the format below
var today = "06/14/2016"
How do I remove the time from getstatusdate and make it look like "06/14/2016"
I tried this but no luck.
var cleaneddate = getstatusdate.toDateString("MM/dd/yyyy")
In alternative, if you don't want to manage dates but manipulate strings, you can use a regex like this one;
var getstatusdate = $('#statusdate').val();
var myRegexp = ^(\d\d\/\d\d\/\d\d\d\d)(.*);
var match = myRegexp.exec(getstatusdate);
var cleaneddate = match[1];
match group 1 matches
starting string (^)
with:
2 digit
\
2 digit
\
4 digit
rest it's optional and ignored (=> in match[2])
If you are taking new Date() then like this
var dt = new Date();
var myDate = dt.getDate() + "/" +parseInt(dt.getMonth() + 1) + "/" + dt.getFullYear();
alert(dt); //Tue Jun 14 2016 21:12:07...
alert(myDate); //14/6/2016
else based on your given date, you can use split() as follow
getstatusdate = "6/14/2016 12:00:00 AM"
alert(getstatusdate.split(" ")[0]); //6/14/2016

JavaScript convert string to date time

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)

convert custom date string to date object

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

Categories