Is there a built-in JavaScript function to process a time string? - javascript

To make a time like "2009-05-02 00:00:00" to "2009-05-02".
I know I can achieve this by a regular expression, but is there a built-in function that can do this?

There's no built-in date function that can do that. As a matter of fact if you create a new Date object in JavaScript with that date format, you get an Invalid Date Error.
You are correct in using a regular expression or string manipulation in this case.
Here's a list of all the JavaScript Date Functions.
To simply get the date portion of the string and display it without converting into a Date Object. You can simply do this:
var dateString = "2009-05-02 00:00:00"
alert(dateString.substring(0,10)); // Will show "2009-05-02"
To convert this string into a proper JavaScript Date Object, you can use this snippet:
function sqlTimeStampToDate(timestamp) {
// This function parses SQL datetime string and returns a JavaScript Date object
// The input has to be in this format: 2007-06-05 15:26:02
var regex=/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
var parts=timestamp.replace(regex,"$1 $2 $3 $4 $5 $6").split(' ');
return new Date(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]);
}
The format will be "ddd MMM dd YYYY hh:mm:ss" + TimeOffSet, but you will be able to use any of the standard JavaScript date functions.

See below for two simple methods to get a date format of "2009-05-02", from the initial format, that is "2009-05-02 00:00:00".
<script type="text/javascript">
var mydate, newdate1, newdate2;
mydate = "2009-05-02 00:00:00";
newdate1 = (mydate.split(/ /))[0];
alert('newdate 1: ' + newdate1);
newdate2 = mydate.substr(0,10);
alert('newdate 2: ' + newdate2);
</script>

You might find this helpful:
Return today's date and time
How to use the Date() method to get today's date.
getTime()
Use getTime() to calculate the years since 1970.
setFullYear()
How to use setFullYear() to set a specific date.
toUTCString()
How to use toUTCString() to convert today's date (according to UTC) to a string.
getDay()
Use getDay() and an array to write a weekday, and not just a number.
This is copy-paste from www.w3schools.com since I can't post a link to it...
Or just search Google for "JavaScript date function" or related. Regular expressions are used to match specific parts of strings, which is useful in searching, extraction and replacement, not really anything that would help you with formatting a date.

Related

How to manipulate date time using vanilla javascript

I want to manipulate date which come from the api.
When I use: console.log(dataAPI.dateStation)
I see 2023-01-24T06:00:00.000Z
Is there way to change the date time in this format 2023-01-24 06:00:00
Just I want to remove T character between date and time and remove .000Z at the end.
The simplest way to do it is probably:
new Date(dataAPI.dateStation).toLocaleString()
If what you want is to display it somewhere, it'll automatically adapt the ISO date you have into a localized and readable date (based on timezone and language).
To know more about it and the options, here is the doc: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
If you want to print the date in ISO 8601 format, you can use the 'sv' (Sweden) locale and Date.toLocaleString().
You can also specify whichever IANA timezone you wish to use, I'm using UTC in this case.
const d = '2023-01-24T06:00:00.000Z'
let timestamp = new Date(d).toLocaleString('sv', { timeZone: 'UTC' });
console.log('Timestamp:', timestamp);
Use the javascript date class with toLocaleString
new Date(dataAPI.dateStation).toLocaleString('en-US');
Without installing some third-party library, your best bet is probably to use the string you have (which is the format returned by toISOString() ),and modify it as desired. If it's already a string in the format you gave, you can just call replace on it:
dataAPI.dateStation.replace('T',' ').replace('.00Z','')
If it's a Date object, first call toISOString() to get a string:
dataAPI.dateStation.toISOString().replace('T',' ').replace('.00Z','')
If it's a string in a possibly-different format, call new Date() to get a Date object, then call toISOString() on that, and finally call replace on the result:
new Date(dataAPI.dateStation).toISOString().replace('T',' ').replace('.00Z','')
You can use regular expressions to remove the parts you don't want:
let s = "2023-01-24T06:00:00.000Z"
s = s.replace(/T/, ' ')
s = s.replace(/\.\d{3}Z$/, '')
console.log(s)

How to add time zone to specific format in momentjs?

I am trying to get specific format of datetime with time zone
i am getting string of time format which is shown below
var dateTime = "2020-06-01T01:50:57.000Z CDT"
I need to convert the format in to
const offsetTime = moment(date).add("-0.00", 'hours')
const formatedDate = moment(offsetTime, 'h:mm:ss A')
.utc()
.format('h:mm A')//(1:50 AM)
Required output
(1:50 AM CDT)
Do i need to split the string and get the format or do we have any method to convert it to this format in momentjs
In simple way to say
YYYY-MM-DDTHH:mm:ss.SSS[Z] z To hh:mm A z //format
and if the string contains only 2 character like "CT" instead of CDT how to capture that.
You can zz to get timezone in output. For ex:
moment()..format('h:mm A zz')
More documentation here momentJS
Use the moment-timezone to achieve this. Use the moment constructor to specify the input format, then specifying the required timezone. Finally use moment's format to get the required format
var dateTime = "2020-06-01T01:50:57.000Z CDT";
var timezone = "America/Chicago";
console.log(
moment(dateTime, "YYYY-MM-DD hh:mm:ss zz")
.tz(timezone)
.format("h:mm A zz")
);
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>
Your date string is in ISO format with the 'Z' after seconds indicating that it is in UTC time. I am assuming that the 'CDT' is placed in the string in order to indicate which time zone this should be converted to. If you have control over how this string is represented then I recommend changing it so that you indicate the desired timezone elsewhere and simply store the date in UTC format. This way you can initialize a date or moment object with the ISO string as follows:
var date = moment("2020-06-01T01:50:57.000Z")
It is inconvenient the way it is currently since you cannot initialize it this way:
var date = moment("2020-06-01T01:50:57.000Z CDT")
The only option for handling the date in its current form is to parse it. You can do that like this:
var dateTime = "2020-06-01T01:50:57.000Z CDT"
var trimmed = dateTime.trim() // remove leading and trailing whitespace
var isoString = trimmed.substr(0, trimmed.indexOf(' '))
Which will produce the following string
2020-06-01T01:50:57.000Z
You can use that string I called "isoString" to initialize a date or moment object. The next obstacle is to handle converting that UTC string to a certain timezone (in this case CDT). It is simple if you want to convert the UTC date to the current users timezone since that will happen automatically when you initialize the moment or date object with the ISO date string. Otherwise, you need some way to get the timezone from 'CDT' into the format moment wants which was shown by #vjr12 ("America/Chicago"). The only way to do this is to either store that with the date string or create a mapping. It is much easier to convert from "America/Chicago" to "CDT" than it is to convert from "CDT" to "America/Chicago". Your only option with the current form is to create your own mapping from "CDT" to "America/Chicago". You could do something like:
let tzMap = new Map()
tzMap.set('CDT','America/Chicago')
// Set the rest of your timezones
You would need to do that for all timezones and then you could use the timezone parsed from your date string like this:
var tzAbbr = trimmed.substr(trimmed.indexOf(' ') + 1)
which will grab the "CDT" or "CT" for that matter. Then you could use your mapping like this:
var timezone = tzMap.get(tzAbbr)
timezone will be "America/Chicago" in this case and then you can use #vjr12 solution from here to get the form you want.
Note
I highly recommend that (if you are able) to change the current format of the datestring that you are using. The purpose of using UTC time is to be timezone agnostic so it does not make sense to store the timezone with the UTC string. If you want to preserve the timezone then you would be better off using a format which already embeds the timezone.

How to convert an invalid date string to Javascript date

I fetch invalid date strings from the REST API but i may not fix the REST API. How can i format an invalid date strings like that "20180517T010237" ?
I tried to use moment for that, but i couldnt succeed.
let date = moment("20180517T010237", "YYYY-MM-DD T HH.mm.ss").toDate();
is there any easy way to do that?
The second string you pass moment is the format of the string you're parsing. Your format string has - and spaces that aren't in your input. Remove them:
let date = moment("20180517T010237", "YYYYMMDDTHHmmss").toDate();
Note that it will be parsed in local time. If you want UTC instead, use moment.utc:
let date = moment.utc("20180517T010237", "YYYYMMDDTHHmmss").toDate();
Example:
let date = moment("20180517T010237", "YYYYMMDDTHHmmss").toDate();
console.log(date);
date = moment.utc("20180517T010237", "YYYYMMDDTHHmmss").toDate();
console.log(date);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>

How to convert date time string in formatted date time in extjs

I have a string of Date and Time ("2017-11-29 11:08:43" YYYY-MM-DD hh:mm:ss) like this. I want to convert it into "29-11 11:08"(DD-MM hh:mm) format.
I tried it using below code. But not get any success. have you any solution?
convert: function (idleFrom) {
var date = Ext.Date.parse(idleFrom, "Y-m-d");
return date;
}
first change your string into date format using
var dt = new Date(idleFrom)
than change into you required format using
Ext.Date.format(dt, 'm/d/Y');
follw this link for more format
Hope it will work :)
If you have a string, and want it reformatted, you have to parse the string into a JS date object first, and then format the JS date object into the string representation you need:
var date = Ext.Date.parse("2017-11-29 11:08:43", "Y-m-d H:i:s")
var str = Ext.Date.format(date, "m/d/Y")
Please note that Ext.Date.parse is really picky regarding the format identifier. If the matching between the format identifier and the input string's format is not 100%, your date will be null.
E.g. Ext.Date.parse("2017-11-29 11:08:43", "Y-m-d H:i") will be null because the seconds are in the date string, but missing from the format identifier.

Javascript date string conversion

I have a system that returns a JSON object that contains dates in string format.
These dates are in the format "2012-10-19 06:05:38 GMT" (no... I'm stuck with them like this)
So I need to get this into a date object (d) ready to output as d.toLocaleDateString()
In chrome it works perfectly by just passing the string to a new Date (Bad bad Chrome - makes Eric lazy), but of course it fails in FF and IE
I can fix it by splitting the string but its not pretty and I've not figured out dealing with the offsets from GMT.
There must be a more elegant way...?
I'm sure someone here can do it in one line.
It's not quite a one-liner, but if you know all your dates will be GMT, something like the following should work:
function parseDate(dateString) {
// [y, m, d, hr, min, sec]
var parts = dateString.match(/\d+/g);
// Months are 0-indexed
parts[1] -= 1;
return new Date(Date.UTC.apply(Date, parts));
}
If I were you, and had access to the serverside script gathering that information (and outputting it) I would convert the date into a unix timestamp, and then make Javascript process that using the Date constructor easily.
EDIT: You can use strtotime() function to convert the string date into numeric unix timestamp if you're using PHP.
If you know the exact format, you could use a library such as Moment.js: Documentation for Moment.js.
To parse:
var dateString = "2012-10-19 06:05:38 GMT".replace(" GMT", "");
var date = moment(dateString, "YYYY-MM-DD HH:mm:ss");
You can just parse the dateString manually,and pass the Date the Date constructor exactly:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
var dateString = "2012-10-19 06:05:38 GMT".split(" "),
date = dateString[0].split("-"),
time = dateString[1].split(":");
var dateObj = new Date(date[0],date[1]-1,date[2],time[0],time[1],time[2]);

Categories

Resources