Modifying the date formatting in JavaScript if it is incorrect

Recently, I developed a mobile application that can scan QR-CODEs containing various information, including a date. However, there have been changes in the format of the date within the QR-CODE between previous and new versions. Previously, the date was formatted as mm/dd, but now it is yy-MM-dd.

Currently, my app can only scan either the old or the new version of the labels, but not both simultaneously. I am exploring the possibility of using an if statement to detect the old format and convert it to the new one. Here is an example of the code that successfully scans the new labels:

(function(){
'use strict';

var app = angular.module('Controllers', []);
var baseUrl = 'https://apps.laticrete.com/LSCWebApiService/lscapi/';

app.controller('BarcodeCtrl', ['$scope', '$state', '$stateParams', '$http', 'alertsManager', '$timeout', 'localStorageService', '$cordovaBarcodeScanner', '$cordovaGeolocation', '$filter',
    function($scope, $state, $stateParams, $http, alertsManager, $timeout, localStorageService, $cordovaBarcodeScanner, $cordovaGeolocation, $filter) {
        var SessionId = localStorageService.get('SessionId');

        // Get GeoLocation
        $cordovaGeolocation
            .getCurrentPosition()
            .then(function(position) {
                $scope.lat = position.coords.latitude;
        $scope.long = position.coords.longitude;
            });

document.addEventListener("deviceready", function() {
    $scope.scanMaterial = function() {


        $cordovaBarcodeScanner
            .scan()
            .then(function(result) {

                var codeArray = result.text.split(',');
                $scope.SKU = codeArray[1].replace("I:", "").trim();
                $scope.ControlNumber = codeArray[0].replace("W:", "").trim(); 
                //$scope.ManufactureDate = codeArray[2].replace("MFG:", "").trim();
                $scope.ManufactureDate = codeArray[2].replace("MFG:", "20").replace(/(\d{4})(\d{2})(\d{2})/, "$1-$2-$3").trim();

                $scope.BatchCode = codeArray[3].replace("B:", "").trim();

                var dataObj = {
                    SessionId: SessionId,
                    JobId: $stateParams.JobId,
                    ManufactureDate: $scope.ManufactureDate, 
                    BatchCode: $scope.BatchCode,
                    SKU: $scope.SKU,
                    ControlNumber: $scope.ControlNumber,
                    CreatedClient: new Date(),
                    Latitude: $scope.lat,
                    Longitude: $scope.long, 
                    Product: { Id : 1}
                };

                $http.post(baseUrl + 'Material/PostNewMaterial', dataObj)
                    .success(function() {
                        alertsManager.addAlert('Success: You have successfully added material.', 'alert-success');
                        $state.go('^');
                    }).error(function(dataObj) {
                        alertsManager.addAlert('Failure Meesage: ' + JSON.stringify({dataObj:dataObj}), 'alert-danger');
                    });
                    $timeout(function(){
                        alertsManager.clearAlerts();
                    }, 5000);

            }, function(error) {
                console.log("An error has happened " + error);
            });
    };
}, false);


}]);

})();

I specifically need help with the part of the code related to $scope.ManufactureDate.

Thank you for your assistance.

Answer №1

To ensure that the code aligns with one of the specified formats, it is important to perform a validation check and then process it accordingly.

if (codeArray[2].match(/MFG:\d+-\d+-\d+/) !== null) {
    /* The expected format is 'MFG:000-000-000', where \d+ represents one or more numbers */
    ...
}

Alternatively, you have the option to combine these checks into a single regex pattern:

let matches = codeArray[2].match(/MFG:(20(\d{2})-\d{2}-\d{2})|(\d{2}/\d{2}))/);

Refer to String.prototype.match documentation for more information.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The ElementNotInteractableException was thrown because the element could not be accessed via the keyboard when trying to input text into the FirstName field on Facebook

The issue is as follows: Exception encountered in thread "main" org.openqa.selenium.ElementNotInteractableException: Element is not accessible via keyboard Here is the code snippet: System.setProperty("webdriver.gecko.driver"," ...

Exploring Javascript: Understanding the Contrast Between Function and Class

In June 2015, with the introduction of ECMAScript 6, a new syntax for Javascript classes was unveiled. The new syntax is exemplified by the following code snippet: class Polygon { constructor(width, height) { this.width = width; thi ...

What techniques can I employ to ensure that withLatestFrom() effectively interacts with itself?

In my program, I have an intermediate stream that is connected to a source, but it can also trigger events from other sources (such as user input). In another part of my code, there is a derived stream that needs to compare new data from the intermediate w ...

Setting the Datetimepicker to be used with every input field

I currently have four textboxes identified by their unique ids: title, sdate, edate, and pdate. My goal is to assign a Datetimepicker to the textboxes that contain the word 'date' in their id. This means I want the Datetimepicker to be assigned ...

Performing API requests in NextJS using Prisma on a client-side page

Currently, I am faced with a challenge in fetching data from my database on a NextJS page designated as a client page using "use client" as required by the theme I am working with. At the moment, I have a page that fetches data from the database and redire ...

Transform the array into an object containing corresponding key-value pairs

In my dataset, I have an array containing various values: [ { "factor": { "data": "f1", "val": [ "val1" ] } }, { "factor": { "data": "f2", "val": [ "val2" ] ...

Stop the time-dependent function from executing within a specific condition

Here is the code snippet I am currently working with: var w = $(window); var $navbar = $('.navbar'); var didScroll = false; w.on('scroll', function(){ didScroll = true; }); function AddScrollHeader(pxFromTop) { setInterval(fun ...

Error: Unable to access the 'CustomerId' property because it is undefined

Recently, I made some updates to my website. As part of the upgrade process, I switched to AngularJS v1.7.6 and JQuery v1.12.1. However, after making these changes, I encountered an error in my console log. TypeError: Cannot read property 'CustomerId ...

Incorporating Checkbox Value into Textbox with classic ASP and jQuery

Here is a glimpse of the code I've written: response.write "<th align=left><font size=2>" response.write "1. <input type=checkbox class='checkboxes' value='ORG'>Organization" response.write "</font> ...

Dealing with Typescript (at-loader) compilation issues within a WebPack environment

Currently, I am using Visual Studio 2017 for writing an Angular SPA, but I rely on WebPack to run it. The current setup involves VS building the Typescript into JS, which is then utilized by WebPack to create the build artifact. However, I am looking to t ...

Trigger ExtJS input file event when dialogue window is closed

How can we capture the event when a file is selected in an open dialogue box and the OK button is clicked in extjs? **Off topic, the field does not stretch from its normal width. xtype: 'textfield', fieldLabel: 'New (JPG or ...

Issue with unit testing in Firestore: Anticipated data type was supposed to be 'DocumentReference', however, what was received was a unique Firestore object

I am trying to execute unit tests for Firestore. Below is the code snippet I am using: import { getDoc, setDoc } from "@firebase/firestore"; import { assertFails, assertSucceeds, initializeTestEnvironment, RulesTestEnvironment, } from &qu ...

What could be causing an error in a scroll handler when using React's setState function?

Upon reaching the bottom of the page and scrolling back up, an error is thrown by React stating "TypeError: _this.setState is not a function" The scroll handler in question monitors the position of the client on the page. If the client is within the home ...

steps for including a JS file into Next.js pages

Is it possible to directly import the bootstrap.bundle.js file from the node_modules/bootstrap directory? import "bootstrap/dist/css/bootstrap.rtl.min.css"; function MyApp({ Component, pageProps }) { return ( <> <Script src="node_m ...

Nextjs: where all roads lead back to the homepage

Having an issue in my app where all redirects keep leading back to the homepage. The problem seems to stem from my Navbar.js component, as shown below. Despite adding the required route in the Link tag for next-js, both client and server compilation is suc ...

How come pagination links in Vue.js 2 return JSON when clicked?

My question relates to having 2 specific components: Firstly, there is a component called SearchResultVue.vue. The structure of this component is as follows : <template> ... <span class="pull-right" v-show="totalall>8"> ...

Unexpected behavior observed in while loop with dual conditions

To break the while loop, I need two conditions to be met - res must not be undefined, which only happens when the status code is 200, and obj.owner needs to match a specific value I have set. Since it takes a few seconds for the owner on that page to updat ...

CSS styling failing to meet desired expectations

Two different elements from different panels are using the same CSS styles, but one displays the desired text while the other does not. The CSS file in question is named grid.css. To see the issue firsthand on my live website, please visit: I am uncertai ...

Escaping an equal sign in JavaScript when using PHP

I am currently working on the following code snippet: print "<TR><TD>".$data->pass_name."</TD><TD><span id='credit'>".$data->credit_left."</span></TD><TD><input type='button' val ...

Array scripts are removed once data has been extracted from the CSV file

Having trouble reading a CSV file using file reader in Javascript. I wrote a script that declares arrays and updates them as the file is read. However, once the reading is complete, all data from the arrays gets wiped out. I'm quite new to JS and can& ...